<?php
/**
 * Analytics Dashboard Template
 * Displays visitor stats with Tailwind CSS styling and tabbed navigation
 */

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

$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';

// Localized month abbreviations + AM/PM tokens for the client-side date
// formatter (fmtDate, used in the visitor/journey modals). Sourced from
// WordPress's own locale data so dashboard dates follow the site language
// without adding month or meridiem strings to this plugin's translations.
global $wp_locale;
$kantan_js_months = array();
for ($m = 1; $m <= 12; $m++) {
    $kantan_js_months[] = $wp_locale->get_month_abbrev($wp_locale->get_month($m));
}
$kantan_js_months_json = wp_json_encode(array_values($kantan_js_months));
$kantan_js_ampm = array(
    'am' => $wp_locale->get_meridiem('AM') ?: 'AM',
    'pm' => $wp_locale->get_meridiem('PM') ?: 'PM',
);
?>

<div class="wrap">
    <div class="max-w-[1400px] mx-auto py-8">

        <?php
        $tabs = [
            'overview' => ['label' => __('Overview', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>'],
            'realtime' => ['label' => __('Realtime', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.348 14.652a3.75 3.75 0 010-5.304m5.304 0a3.75 3.75 0 010 5.304M5.106 18.894c-3.808-3.808-3.808-9.98 0-13.788m13.788 0c3.808 3.808 3.808 9.98 0 13.788M12 12h.008v.008H12V12z"></path>'],
            'interactions' => ['label' => __('Interactions', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path>'],
            'journeys' => ['label' => __('Journeys', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7"></path>'],
            'user-data' => ['label' => __('User Data', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>'],
            'settings' => ['label' => __('Settings', 'kantan-analytics'), 'group' => __('Analytics', 'kantan-analytics'), 'icon' => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>'],
        ];
        // Allow companion plugins to register tabs (with group support)
        $tabs = apply_filters('kantan_analytics_dashboard_tabs', $tabs);

        // Group tabs by their group key
        $grouped = [];
        foreach ($tabs as $tab_id => $tab_info) {
            $group = $tab_info['group'] ?? 'Other';
            $grouped[$group][$tab_id] = $tab_info;
        }
        ?>

        <div class="flex gap-8">

            <!-- Left Sidebar Nav -->
            <nav class="w-56 flex-shrink-0" aria-label="<?php esc_attr_e('Tabs', 'kantan-analytics'); ?>">
                <div class="sticky top-8 space-y-6">

                    <!-- Header -->
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">Kantan</h1>
                        <p class="text-gray-400 text-xs mt-1"><?php /* translators: %d: number of days in the reporting period */ printf( esc_html__( 'Last %d days', 'kantan-analytics' ), (int) $days ); ?></p>
                    </div>

                    <!-- Time Period -->
                    <div class="flex flex-wrap gap-1.5">
                        <?php foreach ([7, 30, 90, 365] as $period): ?>
                            <a href="?page=kantan-analytics&days=<?php echo esc_attr($period); ?>&tab=<?php echo esc_attr($current_tab); ?>"
                               class="px-3 py-1 rounded-md text-xs font-medium <?php echo $days === $period ? 'bg-blue-600 text-white' : 'bg-white text-gray-500 hover:bg-gray-100 border border-gray-200'; ?> transition">
                                <?php echo esc_html($period === 365 ? '1Y' : $period . 'D'); ?>
                            </a>
                        <?php endforeach; ?>
                    </div>

                    <!-- Grouped Tabs (accordion) -->
                    <?php
                    $active_group = '';
                    foreach ($grouped as $group_label => $group_tabs) {
                        if (array_key_exists($current_tab, $group_tabs)) {
                            $active_group = $group_label;
                            break;
                        }
                    }
                    foreach ($grouped as $group_label => $group_tabs):
                        $is_active_group = ($group_label === $active_group);
                        $group_key = 'kantan-nav-' . sanitize_title($group_label);
                    ?>
                        <div class="kantan-nav-group" data-group="<?php echo esc_attr($group_key); ?>">
                            <button type="button"
                                class="kantan-nav-group-toggle w-full flex items-center justify-between text-[10px] font-semibold uppercase tracking-wider mb-1 px-1 py-0.5 rounded hover:text-gray-600 transition <?php echo $is_active_group ? 'text-gray-500' : 'text-gray-400'; ?>"
                                aria-expanded="<?php echo $is_active_group ? 'true' : 'false'; ?>">
                                <span><?php echo esc_html($group_label); ?></span>
                                <svg class="kantan-nav-chevron w-3 h-3 transition-transform duration-150 <?php echo $is_active_group ? 'rotate-180' : ''; ?>" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19 9l-7 7-7-7"></path>
                                </svg>
                            </button>
                            <div class="kantan-nav-group-items space-y-0.5 <?php echo $is_active_group ? '' : 'hidden'; ?>">
                                <?php foreach ($group_tabs as $tab_id => $tab_info):
                                    $is_active = $current_tab === $tab_id;
                                ?>
                                    <a href="?page=kantan-analytics&days=<?php echo esc_attr($days); ?>&tab=<?php echo esc_attr($tab_id); ?>"
                                       class="flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium <?php echo $is_active ? 'bg-blue-50 text-blue-700 border border-blue-200' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'; ?> transition">
                                        <svg class="w-4 h-4 flex-shrink-0 <?php echo $is_active ? 'text-blue-500' : 'text-gray-400'; ?>" fill="none" stroke="currentColor" viewBox="0 0 24 24"><?php echo wp_kses($tab_info['icon'], array('path' => array('d' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true, 'stroke-width' => true, 'fill-rule' => true, 'clip-rule' => true, 'fill' => true))); ?></svg>
                                        <?php echo esc_html($tab_info['label']); ?>
                                        <?php if ($tab_id === 'realtime'): ?>
                                            <span id="kantan-realtime-badge" class="hidden ml-auto inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-semibold bg-green-100 text-green-700">
                                                <span class="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"></span>
                                                <span data-count>0</span>
                                            </span>
                                        <?php endif; ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>

                </div>
            </nav>

            <!-- Main Content -->
            <div class="flex-1 min-w-0">

        <?php if ($current_tab === 'overview'):
        // Helper: generate SVG sparkline from data points
        function kantan_sparkline_svg($data, $color = '#3B82F6', $width = 80, $height = 32) {
            if (empty($data) || count($data) < 2) return '';
            $min = min($data);
            $max = max($data);
            $range = $max - $min ?: 1;
            $step = $width / (count($data) - 1);
            $points = array();
            foreach ($data as $i => $val) {
                $x = round($i * $step, 1);
                $y = round($height - (($val - $min) / $range) * ($height - 4) - 2, 1);
                $points[] = "$x,$y";
            }
            $polyline = implode(' ', $points);
            // Fill area
            $fill_points = $polyline . " $width,$height 0,$height";
            return '<svg width="' . $width . '" height="' . $height . '" class="overflow-visible">'
                . '<polyline points="' . $fill_points . '" fill="' . $color . '" fill-opacity="0.1" stroke="none"/>'
                . '<polyline points="' . $polyline . '" fill="none" stroke="' . $color . '" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>'
                . '</svg>';
        }
        // Allowed tags/attrs for kses-escaping the inline sparkline SVGs.
        $kantan_svg_allowed = array(
            'svg'      => array('width' => true, 'height' => true, 'class' => true, 'viewbox' => true),
            'polyline' => array('points' => true, 'fill' => true, 'fill-opacity' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true),
        );
        ?>
        <!-- ==================== OVERVIEW TAB ==================== -->

        <!-- Key Metrics Grid -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
            <!-- Total Visits -->
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium uppercase"><?php esc_html_e('Total Visits', 'kantan-analytics'); ?></p>
                        <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($total_visits); ?></p>
                        <?php if (!empty($bot_filtered_count)): ?>
                            <p class="text-xs text-gray-400 mt-1" title="<?php esc_attr_e('Sessions that bounced in under two seconds with no engagement, excluded from your metrics. Toggle in Settings.', 'kantan-analytics'); ?>">
                                <?php
                                printf(
                                    /* translators: %s: number of suspected-bot sessions filtered out */
                                    esc_html( _n( '%s bot session filtered', '%s bot sessions filtered', $bot_filtered_count, 'kantan-analytics' ) ),
                                    esc_html( number_format($bot_filtered_count) )
                                );
                                ?>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                        <?php echo wp_kses(kantan_sparkline_svg($sparklines['visits'] ?? [], '#3B82F6'), $kantan_svg_allowed); ?>
                    </div>
                </div>
            </div>

            <!-- Avg Duration -->
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium uppercase"><?php esc_html_e('Avg Duration', 'kantan-analytics'); ?></p>
                        <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo esc_html(kantan_format_duration($avg_duration)); ?></p>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                        <?php echo wp_kses(kantan_sparkline_svg($sparklines['duration'] ?? [], '#10B981'), $kantan_svg_allowed); ?>
                    </div>
                </div>
            </div>

            <!-- Bounce Rate -->
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium uppercase"><?php esc_html_e('Bounce Rate', 'kantan-analytics'); ?></p>
                        <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo esc_html($bounce_rate); ?>%</p>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                        <?php echo wp_kses(kantan_sparkline_svg($sparklines['bounce'] ?? [], '#F59E0B'), $kantan_svg_allowed); ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <!-- Organic Traffic -->
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-purple-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium uppercase"><?php esc_html_e('Organic Traffic', 'kantan-analytics'); ?></p>
                        <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($organic_count); ?></p>
                        <p class="text-sm text-gray-500 mt-1"><?php /* translators: %s: number of non-organic visits */ printf( esc_html__( 'vs %s other', 'kantan-analytics' ), number_format($search_count) ); ?></p>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                        <?php echo wp_kses(kantan_sparkline_svg($sparklines['organic'] ?? [], '#8B5CF6'), $kantan_svg_allowed); ?>
                    </div>
                </div>
            </div>

            <!-- AI Assistants -->
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-amber-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium uppercase"><?php esc_html_e('AI Assistants', 'kantan-analytics'); ?></p>
                        <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($ai_count); ?></p>
                        <p class="text-sm text-gray-500 mt-1"><?php /* translators: %s: percentage of visits from AI assistants */ printf( esc_html__( '%s%% of visits', 'kantan-analytics' ), $total_visits > 0 ? round($ai_count / $total_visits * 100, 1) : 0 ); ?></p>
                        <?php if (!empty($ai_breakdown)):
                            $ai_parts = array();
                            foreach (array_slice($ai_breakdown, 0, 3) as $ai_b) {
                                $ai_parts[] = $ai_b->ai_assistant . ' ' . number_format($ai_b->visits);
                            }
                        ?>
                            <p class="text-[11px] text-gray-400 mt-0.5"><?php echo esc_html(implode(' · ', $ai_parts)); ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                        <?php echo wp_kses(kantan_sparkline_svg($sparklines['ai'] ?? [], '#F59E0B'), $kantan_svg_allowed); ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Visits Chart -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-6"><?php esc_html_e('Visits Over Time', 'kantan-analytics'); ?></h2>
            <div style="position: relative; height: 300px;">
                <canvas id="visitsChart"></canvas>
            </div>
        </div>

        <!-- Two Column Layout -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Traffic Sources -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Traffic Sources', 'kantan-analytics'); ?></h2>
                    <?php kantan_ai_prompts('analytics-overview-traffic-sources'); ?>
                </div>
                <div class="space-y-4">
                    <?php if (empty($traffic_sources)): ?>
                        <p class="text-gray-500 italic"><?php esc_html_e('No traffic data yet', 'kantan-analytics'); ?></p>
                    <?php else: ?>
                        <?php foreach ($traffic_sources as $source):
                            $percentage = $total_visits > 0 ? round(($source->visits / $total_visits) * 100, 1) : 0;
                            $color_map = ['organic' => 'bg-green-500', 'direct' => 'bg-blue-500', 'referral' => 'bg-purple-500', 'social' => 'bg-pink-500', 'ai' => 'bg-amber-500'];
                            $color = $color_map[$source->traffic_source] ?? 'bg-gray-500';
                        ?>
                            <div>
                                <div class="flex justify-between items-center mb-1">
                                    <span class="text-gray-700 font-medium capitalize"><?php echo esc_html(kantan_traffic_source_label($source->traffic_source)); ?></span>
                                    <span class="text-gray-600"><?php echo number_format($source->visits); ?> <span class="text-sm">(<?php echo esc_html($percentage); ?>%)</span></span>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-2">
                                    <div class="<?php echo esc_attr($color); ?> h-2 rounded-full" style="width: <?php echo esc_attr($percentage); ?>%"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Top Referrers -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Top Referrers', 'kantan-analytics'); ?></h2>
                    <div class="flex items-center gap-3">
                        <?php if ($referrer_total > count($top_referrers)): ?>
                            <button type="button" id="kantan-referrers-all-open" class="text-sm font-medium text-blue-600 hover:text-blue-800 transition">
                                <?php
                                printf(
                                    /* translators: %s: total number of referrers, e.g. "47". */
                                    esc_html__('View all %s', 'kantan-analytics'),
                                    esc_html(number_format($referrer_total))
                                );
                                ?>
                            </button>
                        <?php endif; ?>
                        <?php kantan_ai_prompts('analytics-overview-referrers'); ?>
                    </div>
                </div>
                <div class="space-y-3">
                    <?php if (empty($top_referrers)): ?>
                        <p class="text-gray-500 italic"><?php esc_html_e('No referrer data yet', 'kantan-analytics'); ?></p>
                    <?php else: ?>
                        <?php foreach ($top_referrers as $referrer): ?>
                            <div class="flex items-center py-3 border-b border-gray-100 last:border-0 cursor-pointer hover:bg-gray-50 rounded-lg px-2 -mx-2 transition kantan-referrer-link" data-referrer-domain="<?php echo esc_attr($referrer->domain); ?>">
                                <div class="min-w-0 flex-1 mr-4">
                                    <p class="text-sm font-medium text-gray-900 truncate"><?php echo esc_html($referrer->domain); ?></p>
                                </div>
                                <svg class="w-4 h-4 text-gray-300 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
                                <span class="flex-shrink-0 px-3 py-1 bg-blue-100 text-blue-800 text-sm font-medium rounded-full"><?php echo number_format($referrer->visits); ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if (!empty($country_breakdown)):
            $kantan_country_max = max(array_map(function ($c) { return (int) $c->visits; }, $country_breakdown));
        ?>
        <!-- Top Countries -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Top Countries', 'kantan-analytics'); ?></h2>
            </div>
            <div class="space-y-3">
                <?php foreach ($country_breakdown as $c):
                    $pct = $kantan_country_max > 0 ? round(($c->visits / $kantan_country_max) * 100) : 0;
                ?>
                    <div class="flex items-center gap-3">
                        <span class="text-lg flex-shrink-0" aria-hidden="true"><?php echo esc_html(kantan_country_flag($c->country)); ?></span>
                        <span class="text-sm font-medium text-gray-900 w-40 flex-shrink-0 truncate"><?php echo esc_html(kantan_country_name($c->country)); ?></span>
                        <div class="flex-1 bg-gray-100 rounded-full h-2.5 min-w-0">
                            <div class="bg-blue-500 h-2.5 rounded-full" style="width: <?php echo esc_attr($pct); ?>%"></div>
                        </div>
                        <span class="text-sm text-gray-500 w-12 text-right flex-shrink-0"><?php echo number_format($c->visits); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Top Pages -->
        <div class="bg-white rounded-xl shadow-md p-6">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Most Visited Pages', 'kantan-analytics'); ?></h2>
                <?php kantan_ai_prompts('analytics-overview-pages'); ?>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Page', 'kantan-analytics'); ?></th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Views', 'kantan-analytics'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($top_pages)): ?>
                            <tr><td colspan="2" class="px-6 py-4 text-center text-gray-500 italic"><?php esc_html_e('No page data yet', 'kantan-analytics'); ?></td></tr>
                        <?php else: ?>
                            <?php foreach ($top_pages as $page): ?>
                                <tr class="hover:bg-gray-50 cursor-pointer kantan-page-link" data-page-url="<?php echo esc_attr($page->page_url); ?>" data-page-title="<?php echo esc_attr($page->page_title ?: __('Untitled', 'kantan-analytics')); ?>">
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium text-gray-900"><?php echo esc_html($page->page_title ?: __('Untitled', 'kantan-analytics')); ?></div>
                                        <div class="text-sm text-gray-500 truncate" style="max-width: 500px;"><?php echo esc_html($page->page_url); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-3 py-1 inline-flex text-sm leading-5 font-semibold rounded-full bg-blue-100 text-blue-800"><?php echo number_format($page->views); ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Recommended Next Actions -->
        <?php if (!empty($recommendations)): ?>
        <div class="mt-8">
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center gap-2 mb-4">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                    <h2 class="text-lg font-bold text-gray-900"><?php esc_html_e('Recommended Next Actions', 'kantan-analytics'); ?></h2>
                </div>
                <div class="space-y-3">
                    <?php foreach ($recommendations as $rec):
                        $priority_colors = [
                            'high'   => 'border-red-400 bg-red-50',
                            'medium' => 'border-amber-400 bg-amber-50',
                            'low'    => 'border-green-400 bg-green-50',
                        ];
                        $pill_colors = [
                            'high'   => 'bg-red-100 text-red-700',
                            'medium' => 'bg-amber-100 text-amber-700',
                            'low'    => 'bg-green-100 text-green-700',
                        ];
                        $border = $priority_colors[$rec['priority']] ?? 'border-gray-300 bg-gray-50';
                        $pill = $pill_colors[$rec['priority']] ?? 'bg-gray-100 text-gray-700';
                    ?>
                        <div class="border-l-4 <?php echo esc_attr($border); ?> rounded-r-lg p-4">
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <h3 class="text-sm font-semibold text-gray-900"><?php echo esc_html($rec['title']); ?></h3>
                                        <?php if (!empty($rec['metric'])): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo esc_attr($pill); ?>"><?php echo esc_html($rec['metric']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-sm text-gray-600"><?php echo esc_html($rec['action']); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (function_exists('kantan_render_seo_upsell')) { kantan_render_seo_upsell(array(
            'heading' => __('Know which keywords drive this traffic', 'kantan-analytics'),
            'body'    => __("You can see how many visitors arrive from organic search. Kantan SEO reveals the exact keywords and rankings behind them \xe2\x80\x94 and which pages are gaining or slipping.", 'kantan-analytics'),
        )); } ?>

        <?php elseif ($current_tab === 'realtime'): ?>
        <!-- ==================== REALTIME TAB ==================== -->

        <div class="space-y-6">

            <!-- Header with countdown + manual refresh -->
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Realtime Visitors', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Active in the last 5 minutes — refreshes every 30 seconds.', 'kantan-analytics'); ?></p>
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-xs text-gray-500"><?php esc_html_e('Next refresh in', 'kantan-analytics'); ?> <span id="kantan-realtime-countdown" class="font-mono text-gray-700 font-medium">30s</span></span>
                    <button type="button" id="kantan-realtime-refresh" class="px-3 py-1.5 text-xs font-medium bg-white border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition"><?php esc_html_e('Refresh now', 'kantan-analytics'); ?></button>
                </div>
            </div>

            <!-- Big count card -->
            <div class="bg-white rounded-xl shadow-sm border p-8">
                <div class="flex items-center justify-center gap-4">
                    <span class="relative flex h-3 w-3">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
                    </span>
                    <span class="text-6xl font-bold text-gray-900 tabular-nums" id="kantan-realtime-count">0</span>
                </div>
                <p class="text-gray-500 text-sm mt-3 text-center"><?php esc_html_e('visitors active right now', 'kantan-analytics'); ?></p>
            </div>

            <!-- Active visitor table -->
            <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Visitor', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Current Page', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Source', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Pages', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Session Age', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Last Seen', 'kantan-analytics'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="kantan-realtime-tbody" class="divide-y divide-gray-200">
                            <!-- rows injected by the global poller -->
                        </tbody>
                    </table>
                </div>
                <div id="kantan-realtime-empty" class="hidden text-center py-16 text-gray-500">
                    <svg class="w-12 h-12 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.348 14.652a3.75 3.75 0 010-5.304m5.304 0a3.75 3.75 0 010 5.304M5.106 18.894c-3.808-3.808-3.808-9.98 0-13.788m13.788 0c3.808 3.808 3.808 9.98 0 13.788"/></svg>
                    <p class="text-sm"><?php esc_html_e('No visitors active right now.', 'kantan-analytics'); ?></p>
                    <p class="text-xs mt-1"><?php esc_html_e('Showing activity from the last 5 minutes.', 'kantan-analytics'); ?></p>
                </div>
            </div>

        </div>

        <?php elseif ($current_tab === 'interactions'): ?>
        <!-- ==================== INTERACTIONS TAB ==================== -->

        <!-- Click Tracking & Scroll Depth Section -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Click Regions Heatmap -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Click Regions', 'kantan-analytics'); ?></h2>
                    <span class="text-sm text-gray-500"><?php /* translators: %s: total number of clicks */ printf( esc_html__( '%s total clicks', 'kantan-analytics' ), number_format($total_clicks) ); ?></span>
                </div>
                <?php if ($total_clicks > 0):
                    $max_clicks = max($click_regions);
                    $region_labels = [__('Top Left', 'kantan-analytics'), __('Top Center', 'kantan-analytics'), __('Top Right', 'kantan-analytics'), __('Middle Left', 'kantan-analytics'), __('Center', 'kantan-analytics'), __('Middle Right', 'kantan-analytics'), __('Bottom Left', 'kantan-analytics'), __('Bottom Center', 'kantan-analytics'), __('Bottom Right', 'kantan-analytics')];
                ?>
                    <div class="grid grid-cols-3 gap-2 mb-4">
                        <?php for ($i = 1; $i <= 9; $i++):
                            $clicks = $click_regions[$i];
                            $intensity = $max_clicks > 0 ? ($clicks / $max_clicks) : 0;
                            $bg_class = $intensity > 0.66 ? 'bg-red-500' : ($intensity > 0.33 ? 'bg-orange-400' : 'bg-blue-300');
                            if ($clicks == 0) $bg_class = 'bg-gray-100';
                            $clickable = $clicks > 0;
                            $cell_class = $bg_class . ' rounded-lg p-4 text-center transition-all hover:scale-105' . ($clickable ? ' cursor-pointer kantan-region-link' : '');
                            $cell_title = $region_labels[$i-1] . ($clickable ? __(' — click to see what was clicked here', 'kantan-analytics') : '');
                        ?>
                            <div class="<?php echo esc_attr($cell_class); ?>" title="<?php echo esc_attr($cell_title); ?>"<?php if ($clickable): ?> data-region="<?php echo esc_attr($i); ?>" data-region-label="<?php echo esc_attr($region_labels[$i-1]); ?>"<?php endif; ?>>
                                <div class="text-lg font-bold <?php echo $clicks > 0 ? 'text-white' : 'text-gray-400'; ?>"><?php echo number_format($clicks); ?></div>
                                <div class="text-xs <?php echo $clicks > 0 ? 'text-white/80' : 'text-gray-400'; ?>"><?php echo esc_html($region_labels[$i-1]); ?></div>
                            </div>
                        <?php endfor; ?>
                    </div>
                    <p class="text-sm text-gray-500 text-center"><?php esc_html_e('Click a region to see exactly what was clicked there', 'kantan-analytics'); ?></p>
                <?php else: ?>
                    <div class="text-center py-8">
                        <svg class="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path>
                        </svg>
                        <p class="text-gray-500 italic"><?php esc_html_e('No click data yet', 'kantan-analytics'); ?></p>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Scroll Depth -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Scroll Depth', 'kantan-analytics'); ?></h2>
                    <span class="text-sm text-gray-500"><?php /* translators: %s: average scroll depth percentage */ printf( esc_html__( 'Avg: %s%%', 'kantan-analytics' ), esc_html($avg_scroll_depth) ); ?></span>
                </div>
                <?php if ($scroll_distribution && $scroll_distribution->total > 0):
                    $depths = ['0-25%' => $scroll_distribution->depth_25, '26-50%' => $scroll_distribution->depth_50, '51-75%' => $scroll_distribution->depth_75, '76-100%' => $scroll_distribution->depth_100];
                    $colors = ['bg-red-400', 'bg-orange-400', 'bg-yellow-400', 'bg-green-500'];
                    $i = 0;
                ?>
                    <div class="space-y-4">
                        <?php foreach ($depths as $label => $count):
                            $percentage = round(($count / $scroll_distribution->total) * 100, 1);
                        ?>
                            <div>
                                <div class="flex justify-between items-center mb-1">
                                    <span class="text-gray-700 font-medium"><?php echo esc_html($label); ?></span>
                                    <span class="text-gray-600"><?php echo number_format($count); ?> <span class="text-sm">(<?php echo esc_html($percentage); ?>%)</span></span>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-3">
                                    <div class="<?php echo esc_attr($colors[$i]); ?> h-3 rounded-full transition-all" style="width: <?php echo esc_attr($percentage); ?>%"></div>
                                </div>
                            </div>
                        <?php $i++; endforeach; ?>
                    </div>
                    <p class="text-sm text-gray-500 text-center mt-4"><?php esc_html_e('How far users scroll down pages', 'kantan-analytics'); ?></p>
                <?php else: ?>
                    <div class="text-center py-8">
                        <svg class="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
                        </svg>
                        <p class="text-gray-500 italic"><?php esc_html_e('No scroll data yet', 'kantan-analytics'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Scroll Depth by Page -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-1"><?php esc_html_e('Scroll Depth by Page', 'kantan-analytics'); ?></h2>
            <?php if (empty($scroll_by_page)): ?>
                <p class="text-gray-500 italic text-center py-8"><?php esc_html_e('No scroll data yet', 'kantan-analytics'); ?></p>
            <?php else: ?>
                <p class="text-sm text-gray-500 mb-6"><?php esc_html_e('How far visitors actually scroll on each page — the site-wide average above hides which pages get read and which get abandoned. Click a page for full detail.', 'kantan-analytics'); ?></p>
                <div class="space-y-3">
                    <?php foreach ($scroll_by_page as $sp):
                        $avg  = (int) round((float) $sp->avg_scroll);
                        $path = wp_parse_url($sp->page_url, PHP_URL_PATH) ?: '/';
                        $bar  = $avg >= 70 ? 'bg-green-500' : ($avg >= 40 ? 'bg-yellow-400' : 'bg-red-400');
                    ?>
                        <div class="cursor-pointer hover:bg-gray-50 rounded-lg px-2 -mx-2 py-1.5 kantan-page-link" data-page-url="<?php echo esc_attr($sp->page_url); ?>" data-page-title="<?php echo esc_attr($sp->page_title ?: $path); ?>">
                            <div class="flex items-center justify-between mb-1 gap-3">
                                <span class="text-sm font-medium text-gray-800 truncate" title="<?php echo esc_attr($sp->page_url); ?>"><?php echo esc_html($sp->page_title ?: $path); ?></span>
                                <span class="text-sm text-gray-600 flex-shrink-0 whitespace-nowrap"><?php /* translators: 1: average scroll percentage, 2: number of views */ printf( esc_html__( '%1$s%% avg · %2$s views', 'kantan-analytics' ), esc_html($avg), number_format($sp->views) ); ?></span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="<?php echo esc_attr($bar); ?> h-2 rounded-full" style="width: <?php echo esc_attr(max(2, min(100, $avg))); ?>%"></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Top Clicked Elements -->
        <div class="bg-white rounded-xl shadow-md p-6">
            <div class="flex items-center justify-between mb-1">
                <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Top Clicked Elements', 'kantan-analytics'); ?></h2>
                <?php kantan_ai_prompts('analytics-interactions-clicks'); ?>
            </div>
            <?php if (empty($top_clicked_elements)): ?>
                <p class="text-gray-500 italic text-center py-8"><?php esc_html_e('No click data yet', 'kantan-analytics'); ?></p>
            <?php else: ?>
                <p class="text-sm text-gray-500 mb-6"><?php esc_html_e('The same control is merged across pages. Click a row to see which pages it was clicked on.', 'kantan-analytics'); ?></p>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Element', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Type', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Pages', 'kantan-analytics'); ?></th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Clicks', 'kantan-analytics'); ?></th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($top_clicked_elements as $element): ?>
                                <tr class="hover:bg-gray-50 cursor-pointer kantan-element-link" data-element-text="<?php echo esc_attr($element->element_text); ?>">
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900 truncate" style="max-width: 400px;"><?php echo esc_html($element->element_text ?: __('(no text)', 'kantan-analytics')); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 py-1 text-xs font-mono bg-gray-100 text-gray-700 rounded">&lt;<?php echo esc_html($element->element_tag); ?>&gt;</span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo number_format($element->page_count ?? 0); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-3 py-1 inline-flex text-sm leading-5 font-semibold rounded-full bg-orange-100 text-orange-800"><?php echo number_format($element->clicks); ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Recommended Next Actions -->
        <?php if (!empty($recommendations)): ?>
        <div class="mt-8">
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center gap-2 mb-4">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                    <h2 class="text-lg font-bold text-gray-900"><?php esc_html_e('Recommended Next Actions', 'kantan-analytics'); ?></h2>
                </div>
                <div class="space-y-3">
                    <?php foreach ($recommendations as $rec):
                        $priority_colors = [
                            'high'   => 'border-red-400 bg-red-50',
                            'medium' => 'border-amber-400 bg-amber-50',
                            'low'    => 'border-green-400 bg-green-50',
                        ];
                        $pill_colors = [
                            'high'   => 'bg-red-100 text-red-700',
                            'medium' => 'bg-amber-100 text-amber-700',
                            'low'    => 'bg-green-100 text-green-700',
                        ];
                        $border = $priority_colors[$rec['priority']] ?? 'border-gray-300 bg-gray-50';
                        $pill = $pill_colors[$rec['priority']] ?? 'bg-gray-100 text-gray-700';
                    ?>
                        <div class="border-l-4 <?php echo esc_attr($border); ?> rounded-r-lg p-4">
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <h3 class="text-sm font-semibold text-gray-900"><?php echo esc_html($rec['title']); ?></h3>
                                        <?php if (!empty($rec['metric'])): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo esc_attr($pill); ?>"><?php echo esc_html($rec['metric']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-sm text-gray-600"><?php echo esc_html($rec['action']); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php elseif ($current_tab === 'journeys'): ?>
        <!-- ==================== JOURNEYS TAB ==================== -->

        <!-- Visitor Profiles -->
        <?php if (empty($visitor_profiles)): ?>
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="text-center py-12">
                    <svg class="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    </svg>
                    <h2 class="text-xl font-bold text-gray-900 mb-2"><?php esc_html_e('No Visitor Data Yet', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 max-w-md mx-auto"><?php esc_html_e('Visitor profiles will appear here as people visit the site. Each visitor gets a unique identity so you can follow their journey across multiple sessions.', 'kantan-analytics'); ?></p>
                </div>
            </div>
        <?php else: ?>
            <div class="space-y-6">
                <?php foreach ($visitor_profiles as $visitor):
                    $device = '';
                    if (!empty($visitor->sessions)) {
                        $sw = intval($visitor->sessions[0]->screen_width ?? 0);
                        $device = $sw <= 480 ? __('Mobile', 'kantan-analytics') : ($sw <= 1024 ? __('Tablet', 'kantan-analytics') : __('Desktop', 'kantan-analytics'));
                    }
                    $source_list = array_filter(explode(',', $visitor->sources ?? ''));
                ?>
                    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
                        <!-- Visitor Header -->
                        <div class="px-6 py-4 border-b bg-gray-50 flex items-center justify-between flex-wrap gap-3">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 font-bold text-sm">
                                    <?php echo esc_html(strtoupper(substr($visitor->display_name, 0, 1))); ?>
                                </div>
                                <div>
                                    <h3 class="font-bold text-gray-900 flex items-center gap-2">
                                        <span class="kantan-visitor-name kantan-visitor-history cursor-pointer hover:text-blue-600" data-visitor-id="<?php echo esc_attr($visitor->visitor_id); ?>" title="<?php esc_attr_e('View full visit history', 'kantan-analytics'); ?>"><?php echo esc_html($visitor->display_name); ?></span>
                                        <?php if ($visitor->is_identified): ?>
                                            <span class="bg-green-100 text-green-700 text-xs px-2 py-0.5 rounded font-medium"><?php esc_html_e('Identified', 'kantan-analytics'); ?></span>
                                        <?php endif; ?>
                                        <button type="button" class="kantan-rename-visitor text-gray-400 hover:text-blue-600 transition" data-visitor-id="<?php echo esc_attr($visitor->visitor_id); ?>" title="<?php esc_attr_e('Rename visitor', 'kantan-analytics'); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                        </button>
                                    </h3>
                                    <p class="text-sm text-gray-500">
                                        <?php
                                        /* translators: %s: number of visits */
                                        printf( esc_html( _n( '%s visit', '%s visits', $visitor->total_sessions, 'kantan-analytics' ) ), esc_html($visitor->total_sessions) );
                                        ?>
                                        · <?php
                                        /* translators: %s: date the visitor was first seen, e.g. "Jun 3" */
                                        printf( esc_html__( 'First seen %s', 'kantan-analytics' ), esc_html(gmdate('M j', strtotime($visitor->first_seen))) );
                                        ?>
                                        <?php if ($device): ?> · <?php echo esc_html($device); ?><?php endif; ?>
                                    </p>
                                </div>
                            </div>
                            <div class="flex gap-1">
                                <?php foreach ($source_list as $src):
                                    $source_colors = ['organic' => 'bg-green-100 text-green-800', 'direct' => 'bg-blue-100 text-blue-800', 'referral' => 'bg-purple-100 text-purple-800', 'social' => 'bg-pink-100 text-pink-800', 'ai' => 'bg-amber-100 text-amber-800'];
                                    $src = trim($src);
                                ?>
                                    <span class="<?php echo esc_attr($source_colors[$src] ?? 'bg-gray-100 text-gray-800'); ?> px-2 py-0.5 rounded text-xs font-medium capitalize"><?php echo esc_html(kantan_traffic_source_label($src)); ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Session Timeline -->
                        <div class="px-6 py-4">
                            <div class="space-y-4">
                                <?php foreach ($visitor->sessions as $si => $session):
                                    $source_colors = ['organic' => 'border-green-400', 'direct' => 'border-blue-400', 'referral' => 'border-purple-400', 'social' => 'border-pink-400', 'ai' => 'border-amber-400'];
                                    $border = $source_colors[$session->traffic_source] ?? 'border-gray-300';
                                ?>
                                    <div class="border-l-3 <?php echo esc_attr($border); ?> pl-4 border-l-[3px]">
                                        <div class="flex items-center gap-3 text-sm text-gray-500 mb-2 flex-wrap">
                                            <span class="font-medium text-gray-700"><?php echo esc_html(gmdate('M j, g:i A', strtotime($session->visit_date))); ?></span>
                                            <span class="capitalize"><?php echo esc_html(kantan_traffic_source_label($session->traffic_source ?: 'unknown')); ?></span>
                                            <?php
                                            $utm_parts = array_filter(array(
                                                'source'   => $session->utm_source ?? '',
                                                'medium'   => $session->utm_medium ?? '',
                                                'campaign' => $session->utm_campaign ?? '',
                                                'term'     => $session->utm_term ?? '',
                                                'content'  => $session->utm_content ?? '',
                                            ));
                                            if (!empty($utm_parts)):
                                                $utm_tooltip = '';
                                                foreach ($utm_parts as $k => $v) { $utm_tooltip .= $k . ': ' . $v . "\n"; }
                                                if (!empty($utm_parts['campaign'])) {
                                                    $utm_display = $utm_parts['campaign'];
                                                } else {
                                                    $utm_display = implode(' / ', array_filter(array($utm_parts['source'] ?? '', $utm_parts['medium'] ?? '')));
                                                }
                                            ?>
                                                <span class="inline-flex items-center gap-1 bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded text-xs font-medium" title="<?php echo esc_attr(trim($utm_tooltip)); ?>">
                                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"></path></svg>
                                                    <?php echo esc_html($utm_display); ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($session->visit_duration > 0): ?>
                                                <span><?php echo esc_html(kantan_format_duration($session->visit_duration)); ?></span>
                                            <?php endif; ?>
                                            <?php if ($session->is_bounce): ?>
                                                <span class="text-orange-500 text-xs"><?php esc_html_e('bounce', 'kantan-analytics'); ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <!-- Page path -->
                                        <div class="flex items-center gap-1 flex-wrap mb-1">
                                            <?php foreach ($session->pages as $pi => $page):
                                                $is_first = $pi === 0;
                                                $is_last = $pi === count($session->pages) - 1;
                                                $page_class = $is_first ? 'bg-green-50 text-green-700 border border-green-200' : ($is_last && count($session->pages) > 1 ? 'bg-red-50 text-red-700 border border-red-200' : 'bg-gray-50 text-gray-600 border border-gray-200');
                                                $path = wp_parse_url($page->page_url, PHP_URL_PATH) ?: '/';
                                                if (strlen($path) > 25) $path = '...' . substr($path, -22);
                                            ?>
                                                <?php if ($pi > 0): ?><span class="text-gray-300">→</span><?php endif; ?>
                                                <span class="<?php echo esc_attr($page_class); ?> px-2 py-0.5 rounded text-xs cursor-pointer hover:ring-2 hover:ring-blue-300 kantan-page-link" data-page-url="<?php echo esc_attr($page->page_url); ?>" data-page-title="<?php echo esc_attr($page->page_title ?: $page->page_url); ?>" title="<?php echo esc_attr($page->page_title ?: $page->page_url); ?>"><?php echo esc_html($path); ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                        <!-- Conversions -->
                                        <?php if (!empty($session->conversions)): ?>
                                            <?php foreach ($session->conversions as $conv): ?>
                                                <div class="flex items-center gap-2 mt-1">
                                                    <span class="text-amber-500">
                                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path></svg>
                                                    </span>
                                                    <span class="text-xs text-amber-700 font-medium"><?php echo esc_html($conv->conversion_type); ?></span>
                                                    <span class="text-xs text-gray-400"><?php echo esc_html($conv->conversion_label); ?></span>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Page Flow Section -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mt-8">
            <!-- Page Transitions (filtered) -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-bold text-gray-900"><?php esc_html_e('Top Page Transitions', 'kantan-analytics'); ?></h2>
                    <?php kantan_ai_prompts('analytics-journeys-transitions'); ?>
                </div>
                <?php
                // Filter out self-transitions
                $filtered_transitions = array_filter($page_transitions, function($t) {
                    return wp_parse_url($t->from_page, PHP_URL_PATH) !== wp_parse_url($t->to_page, PHP_URL_PATH);
                });
                ?>
                <?php if (empty($filtered_transitions)): ?>
                    <p class="text-gray-500 italic text-center py-4 text-sm"><?php esc_html_e('No transition data yet', 'kantan-analytics'); ?></p>
                <?php else: ?>
                    <div class="space-y-2">
                        <?php foreach ($filtered_transitions as $transition):
                            $from_path = wp_parse_url($transition->from_page, PHP_URL_PATH) ?: '/';
                            $to_path = wp_parse_url($transition->to_page, PHP_URL_PATH) ?: '/';
                            if (strlen($from_path) > 20) $from_path = '...' . substr($from_path, -17);
                            if (strlen($to_path) > 20) $to_path = '...' . substr($to_path, -17);
                        ?>
                            <div class="flex items-center justify-between py-1.5 border-b border-gray-100 last:border-0">
                                <div class="flex items-center gap-2 flex-1 min-w-0">
                                    <span class="bg-blue-50 text-blue-700 px-2 py-0.5 rounded text-xs truncate" title="<?php echo esc_attr($transition->from_page); ?>"><?php echo esc_html($from_path); ?></span>
                                    <span class="text-gray-300">→</span>
                                    <span class="bg-gray-50 text-gray-600 px-2 py-0.5 rounded text-xs truncate" title="<?php echo esc_attr($transition->to_page); ?>"><?php echo esc_html($to_path); ?></span>
                                </div>
                                <span class="ml-2 text-xs font-medium text-gray-500"><?php echo number_format($transition->transitions); ?>×</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Entry & Exit Pages -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-bold text-gray-900"><?php esc_html_e('Entry & Exit Pages', 'kantan-analytics'); ?></h2>
                    <?php kantan_ai_prompts('analytics-journeys-entryexit'); ?>
                </div>
                <div class="grid grid-cols-2 gap-6">
                    <div>
                        <h3 class="text-xs font-semibold text-gray-500 uppercase mb-3 flex items-center gap-2">
                            <span class="w-2 h-2 bg-green-500 rounded-full"></span> <?php esc_html_e('Entry Pages', 'kantan-analytics'); ?>
                        </h3>
                        <?php if (empty($entry_pages)): ?>
                            <p class="text-gray-400 italic text-sm"><?php esc_html_e('No data', 'kantan-analytics'); ?></p>
                        <?php else: ?>
                            <div class="space-y-1.5">
                                <?php foreach ($entry_pages as $page):
                                    $path = wp_parse_url($page->page_url, PHP_URL_PATH) ?: '/';
                                    if (strlen($path) > 20) $path = '...' . substr($path, -17);
                                ?>
                                    <div class="flex justify-between items-center text-sm cursor-pointer hover:bg-gray-50 rounded px-1 -mx-1 kantan-page-link" data-page-url="<?php echo esc_attr($page->page_url); ?>" data-page-title="<?php echo esc_attr($page->page_url); ?>">
                                        <span class="text-gray-700 truncate" title="<?php echo esc_attr($page->page_url); ?>"><?php echo esc_html($path); ?></span>
                                        <span class="text-gray-400 ml-2 text-xs"><?php echo number_format($page->entries); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <h3 class="text-xs font-semibold text-gray-500 uppercase mb-3 flex items-center gap-2">
                            <span class="w-2 h-2 bg-red-500 rounded-full"></span> <?php esc_html_e('Exit Pages', 'kantan-analytics'); ?>
                        </h3>
                        <?php if (empty($exit_pages)): ?>
                            <p class="text-gray-400 italic text-sm"><?php esc_html_e('No data', 'kantan-analytics'); ?></p>
                        <?php else: ?>
                            <div class="space-y-1.5">
                                <?php foreach ($exit_pages as $page):
                                    $path = wp_parse_url($page->page_url, PHP_URL_PATH) ?: '/';
                                    if (strlen($path) > 20) $path = '...' . substr($path, -17);
                                ?>
                                    <div class="flex justify-between items-center text-sm cursor-pointer hover:bg-gray-50 rounded px-1 -mx-1 kantan-page-link" data-page-url="<?php echo esc_attr($page->page_url); ?>" data-page-title="<?php echo esc_attr($page->page_url); ?>">
                                        <span class="text-gray-700 truncate" title="<?php echo esc_attr($page->page_url); ?>"><?php echo esc_html($path); ?></span>
                                        <span class="text-gray-400 ml-2 text-xs"><?php echo number_format($page->exits); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php ob_start(); ?>
        (function() {
            document.querySelectorAll('.kantan-rename-visitor').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var vid = this.getAttribute('data-visitor-id');
                    var nameEl = document.querySelector('.kantan-visitor-name[data-visitor-id="' + vid + '"]');
                    var currentName = nameEl.textContent;
                    var newName = prompt('<?php echo esc_js( __( 'Enter a name for this visitor:', 'kantan-analytics' ) ); ?>', currentName);
                    if (newName && newName !== currentName) {
                        fetch('<?php echo esc_url(rest_url('kantan/v1/visitors/')); ?>' + vid, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                            },
                            body: JSON.stringify({ name: newName })
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(resp) {
                            if (resp.updated) {
                                nameEl.textContent = resp.display_name;
                            }
                        });
                    }
                });
            });
        })();
        <?php kantan_admin_inline_js( ob_get_clean() ); ?>

        <!-- Recommended Next Actions -->
        <?php if (!empty($recommendations)): ?>
        <div class="mt-8">
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center gap-2 mb-4">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                    <h2 class="text-lg font-bold text-gray-900"><?php esc_html_e('Recommended Next Actions', 'kantan-analytics'); ?></h2>
                </div>
                <div class="space-y-3">
                    <?php foreach ($recommendations as $rec):
                        $priority_colors = [
                            'high'   => 'border-red-400 bg-red-50',
                            'medium' => 'border-amber-400 bg-amber-50',
                            'low'    => 'border-green-400 bg-green-50',
                        ];
                        $pill_colors = [
                            'high'   => 'bg-red-100 text-red-700',
                            'medium' => 'bg-amber-100 text-amber-700',
                            'low'    => 'bg-green-100 text-green-700',
                        ];
                        $border = $priority_colors[$rec['priority']] ?? 'border-gray-300 bg-gray-50';
                        $pill = $pill_colors[$rec['priority']] ?? 'bg-gray-100 text-gray-700';
                    ?>
                        <div class="border-l-4 <?php echo esc_attr($border); ?> rounded-r-lg p-4">
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <h3 class="text-sm font-semibold text-gray-900"><?php echo esc_html($rec['title']); ?></h3>
                                        <?php if (!empty($rec['metric'])): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo esc_attr($pill); ?>"><?php echo esc_html($rec['metric']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-sm text-gray-600"><?php echo esc_html($rec['action']); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (function_exists('kantan_render_seo_upsell')) { kantan_render_seo_upsell(array(
            'heading' => __('See what surfaces your top entry pages in search', 'kantan-analytics'),
            'body'    => __('Kantan SEO connects each landing and entry page to the organic keywords and queries that bring searchers to them.', 'kantan-analytics'),
        )); } ?>

        <?php elseif ($current_tab === 'user-data'): ?>
        <!-- ==================== USER DATA TAB ==================== -->

        <?php
        $devices      = kantan_get_device_breakdown($days);
        $browsers     = kantan_get_browser_breakdown($days, 10);
        $os_list      = kantan_get_os_breakdown($days, 10);
        $resolutions  = kantan_get_screen_resolutions($days, 10);

        $total_device_sessions = array_sum(array_map(function($d) { return (int) $d->sessions; }, $devices));

        // Device colors
        $device_colors = [
            'Mobile'  => ['bg' => 'bg-blue-500',   'text' => 'text-blue-600',   'hex' => '#3B82F6'],
            'Tablet'  => ['bg' => 'bg-amber-500',  'text' => 'text-amber-600',  'hex' => '#F59E0B'],
            'Laptop'  => ['bg' => 'bg-emerald-500','text' => 'text-emerald-600','hex' => '#10B981'],
            'Desktop' => ['bg' => 'bg-purple-500', 'text' => 'text-purple-600', 'hex' => '#8B5CF6'],
            'Unknown' => ['bg' => 'bg-gray-400',   'text' => 'text-gray-500',   'hex' => '#9CA3AF'],
        ];

        // Browser colors
        $browser_colors = ['#3B82F6','#10B981','#F59E0B','#8B5CF6','#EF4444','#EC4899','#14B8A6','#F97316','#6366F1','#84CC16'];
        ?>

        <div class="space-y-8">

            <!-- Device Categories -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="flex items-center justify-between">
                    <h2 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Device Categories', 'kantan-analytics'); ?></h2>
                    <?php kantan_ai_prompts('analytics-devices'); ?>
                </div>
                <p class="text-gray-500 text-sm mb-6"><?php esc_html_e('Visitor sessions by screen size — Mobile ≤768px, Tablet 769–1024px, Laptop 1025–1440px, Desktop 1441px+', 'kantan-analytics'); ?></p>

                <?php if (empty($devices)): ?>
                    <p class="text-gray-400 italic text-sm"><?php esc_html_e('No device data yet', 'kantan-analytics'); ?></p>
                <?php else: ?>
                    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        <?php foreach ($devices as $device):
                            $pct = $total_device_sessions > 0 ? round(($device->sessions / $total_device_sessions) * 100, 1) : 0;
                            $colors = $device_colors[$device->device_type] ?? $device_colors['Unknown'];
                        ?>
                            <div class="rounded-lg border p-4">
                                <div class="flex items-center gap-2 mb-2">
                                    <span class="w-3 h-3 rounded-full <?php echo esc_attr($colors['bg']); ?>"></span>
                                    <span class="text-sm font-medium text-gray-700"><?php echo esc_html($device->device_type); ?></span>
                                </div>
                                <p class="text-2xl font-bold text-gray-900"><?php echo number_format($device->sessions); ?></p>
                                <p class="text-xs text-gray-500"><?php /* translators: %s: percentage of sessions */ printf( esc_html__( '%s%% of sessions', 'kantan-analytics' ), esc_html($pct) ); ?></p>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Device bar -->
                    <div class="h-4 rounded-full overflow-hidden flex bg-gray-100">
                        <?php foreach ($devices as $device):
                            $pct = $total_device_sessions > 0 ? ($device->sessions / $total_device_sessions) * 100 : 0;
                            $colors = $device_colors[$device->device_type] ?? $device_colors['Unknown'];
                        ?>
                            <div class="<?php echo esc_attr($colors['bg']); ?> h-full" style="width:<?php echo esc_attr($pct); ?>%" title="<?php echo esc_attr($device->device_type . ': ' . round($pct, 1) . '%'); ?>"></div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Device detail table -->
                    <table class="w-full mt-6 text-sm">
                        <thead>
                            <tr class="border-b text-left text-gray-500">
                                <th class="pb-2 font-medium"><?php esc_html_e('Device', 'kantan-analytics'); ?></th>
                                <th class="pb-2 font-medium text-right"><?php esc_html_e('Sessions', 'kantan-analytics'); ?></th>
                                <th class="pb-2 font-medium text-right"><?php esc_html_e('Avg Duration', 'kantan-analytics'); ?></th>
                                <th class="pb-2 font-medium text-right"><?php esc_html_e('Bounce Rate', 'kantan-analytics'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($devices as $device):
                                $colors = $device_colors[$device->device_type] ?? $device_colors['Unknown'];
                            ?>
                                <tr class="border-b border-gray-50">
                                    <td class="py-2.5 flex items-center gap-2">
                                        <span class="w-2.5 h-2.5 rounded-full <?php echo esc_attr($colors['bg']); ?>"></span>
                                        <span class="font-medium text-gray-900"><?php echo esc_html($device->device_type); ?></span>
                                    </td>
                                    <td class="py-2.5 text-right text-gray-700"><?php echo number_format($device->sessions); ?></td>
                                    <td class="py-2.5 text-right text-gray-700"><?php echo esc_html(kantan_format_duration(round($device->avg_duration))); ?></td>
                                    <td class="py-2.5 text-right text-gray-700"><?php echo esc_html(round($device->bounce_rate, 1)); ?>%</td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>

            <!-- Two Column: Browsers + OS -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

                <!-- Browsers -->
                <div class="bg-white rounded-xl shadow-sm border p-6">
                    <h2 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Browsers', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mb-4"><?php esc_html_e('Detected from user agent strings', 'kantan-analytics'); ?></p>

                    <?php if (empty($browsers)): ?>
                        <p class="text-gray-400 italic text-sm"><?php esc_html_e('No browser data yet', 'kantan-analytics'); ?></p>
                    <?php else:
                        $total_browser_sessions = array_sum(array_map(function($b) { return (int) $b->sessions; }, $browsers));
                    ?>
                        <div class="space-y-3">
                            <?php foreach ($browsers as $i => $browser):
                                $pct   = $total_browser_sessions > 0 ? round(($browser->sessions / $total_browser_sessions) * 100, 1) : 0;
                                $color = $browser_colors[$i % count($browser_colors)];
                            ?>
                                <div>
                                    <div class="flex items-center justify-between text-sm mb-1">
                                        <span class="font-medium text-gray-900"><?php echo esc_html($browser->browser); ?></span>
                                        <span class="text-gray-500"><?php echo number_format($browser->sessions); ?> <span class="text-gray-400">(<?php echo esc_html($pct); ?>%)</span></span>
                                    </div>
                                    <div class="h-2 rounded-full bg-gray-100 overflow-hidden">
                                        <div class="h-full rounded-full" style="width:<?php echo esc_attr($pct); ?>%;background:<?php echo esc_attr($color); ?>"></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Operating Systems -->
                <div class="bg-white rounded-xl shadow-sm border p-6">
                    <h2 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Operating Systems', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mb-4"><?php esc_html_e('Detected from user agent strings', 'kantan-analytics'); ?></p>

                    <?php if (empty($os_list)): ?>
                        <p class="text-gray-400 italic text-sm"><?php esc_html_e('No OS data yet', 'kantan-analytics'); ?></p>
                    <?php else:
                        $total_os_sessions = array_sum(array_map(function($o) { return (int) $o->sessions; }, $os_list));
                    ?>
                        <div class="space-y-3">
                            <?php foreach ($os_list as $i => $os):
                                $pct   = $total_os_sessions > 0 ? round(($os->sessions / $total_os_sessions) * 100, 1) : 0;
                                $color = $browser_colors[$i % count($browser_colors)];
                            ?>
                                <div>
                                    <div class="flex items-center justify-between text-sm mb-1">
                                        <span class="font-medium text-gray-900"><?php echo esc_html($os->os); ?></span>
                                        <span class="text-gray-500"><?php echo number_format($os->sessions); ?> <span class="text-gray-400">(<?php echo esc_html($pct); ?>%)</span></span>
                                    </div>
                                    <div class="h-2 rounded-full bg-gray-100 overflow-hidden">
                                        <div class="h-full rounded-full" style="width:<?php echo esc_attr($pct); ?>%;background:<?php echo esc_attr($color); ?>"></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

            </div>

            <!-- Screen Resolutions -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <h2 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Screen Resolutions', 'kantan-analytics'); ?></h2>
                <p class="text-gray-500 text-sm mb-4"><?php esc_html_e('Top screen sizes by session count', 'kantan-analytics'); ?></p>

                <?php if (empty($resolutions)): ?>
                    <p class="text-gray-400 italic text-sm"><?php esc_html_e('No resolution data yet', 'kantan-analytics'); ?></p>
                <?php else:
                    $max_res_sessions = (int) $resolutions[0]->sessions;
                ?>
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b text-left text-gray-500">
                                <th class="pb-2 font-medium w-8">#</th>
                                <th class="pb-2 font-medium"><?php esc_html_e('Resolution', 'kantan-analytics'); ?></th>
                                <th class="pb-2 font-medium"><?php esc_html_e('Sessions', 'kantan-analytics'); ?></th>
                                <th class="pb-2 font-medium w-1/2"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($resolutions as $i => $res):
                                $bar_pct = $max_res_sessions > 0 ? ($res->sessions / $max_res_sessions) * 100 : 0;
                            ?>
                                <tr class="border-b border-gray-50">
                                    <td class="py-2.5 text-gray-400"><?php echo esc_html($i + 1); ?></td>
                                    <td class="py-2.5 font-mono text-gray-900 font-medium"><?php echo esc_html($res->resolution); ?></td>
                                    <td class="py-2.5 text-gray-700"><?php echo number_format($res->sessions); ?></td>
                                    <td class="py-2.5">
                                        <div class="h-2 rounded-full bg-gray-100 overflow-hidden">
                                            <div class="h-full rounded-full bg-blue-500" style="width:<?php echo esc_attr($bar_pct); ?>%"></div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>

        </div>

        <?php elseif ($current_tab === 'settings'): ?>
        <!-- ==================== SETTINGS TAB ==================== -->

        <div class="space-y-8">

            <!-- Top row: AI Agent + Excluded IPs (50/50) -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

            <!-- AI Agent -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-6">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('AI Agent', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Download an AI agent that can analyze your analytics data — works with Claude Code and Gemini CLI. It connects to your site\'s REST API to read traffic, conversions, and visitor behavior data.', 'kantan-analytics'); ?></p>
                </div>

                <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4 text-sm text-blue-800">
                    <?php echo wp_kses_post( __( '<strong>You only need to download the agent once.</strong> The agent file is the same for every site — install it globally (<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">~/.claude/agents/</code> for Claude Code, <code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">~/.gemini/agents/</code> for Gemini CLI) and reuse it everywhere. To point it at another site, just set that site\'s credentials. After install, it <strong>keeps itself up to date automatically</strong> (it checks for a newer version about once a week) — no need to re-download for updates.', 'kantan-analytics' ) ); ?>
                </div>

                <div class="flex flex-wrap items-center gap-4">
                    <button type="button" id="kantan-download-agent"
                        class="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                        <?php esc_html_e('Download Analytics Agent', 'kantan-analytics'); ?>
                    </button>
                    <button type="button" id="kantan-update-agent"
                        class="inline-flex items-center gap-2 px-4 py-2.5 bg-white border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50 transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
                        <?php esc_html_e('Update agent file (keeps your key)', 'kantan-analytics'); ?>
                    </button>
                    <span id="kantan-agent-status" class="text-sm text-gray-500"></span>
                </div>

                <p class="mt-3 text-xs text-gray-400"><?php esc_html_e('Using a different tool?', 'kantan-analytics'); ?> <button type="button" class="underline hover:text-gray-600" data-codex-open><?php esc_html_e('What about Codex?', 'kantan-analytics'); ?></button></p>

                <details class="mt-5 text-sm text-gray-500">
                    <summary class="cursor-pointer text-gray-600 hover:text-gray-800 font-medium"><?php esc_html_e('What is this?', 'kantan-analytics'); ?></summary>
                    <div class="mt-3 space-y-2 pl-1">
                        <p><?php echo wp_kses_post( __( 'This downloads a Markdown (<code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">.md</code>) agent file for AI coding tools that support subagents — <a href="https://docs.anthropic.com/en/docs/claude-code" target="_blank" class="text-blue-600 underline">Claude Code</a> and <a href="https://github.com/google-gemini/gemini-cli" target="_blank" class="text-blue-600 underline">Gemini CLI</a> both load this exact format.', 'kantan-analytics' ) ); ?></p>
                        <ol class="list-decimal ml-5 space-y-1 mt-2">
                            <li><?php echo wp_kses_post( __( 'Click <strong>Download Analytics Agent</strong> above (once — the file is the same for every site)', 'kantan-analytics' ) ); ?></li>
                            <li><?php esc_html_e('Copy the environment variables from the modal that appears', 'kantan-analytics'); ?></li>
                            <li><?php echo wp_kses_post( __( 'Add the env vars to your <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.zshrc</code> or a project <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">.env</code> file (one set of credentials per site)', 'kantan-analytics' ) ); ?></li>
                            <li><?php echo wp_kses_post( __( 'Place the downloaded file in your agent\'s folder — <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.claude/agents/</code> (Claude Code) or <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.gemini/agents/</code> (Gemini CLI)', 'kantan-analytics' ) ); ?></li>
                            <li><?php echo wp_kses_post( __( 'Invoke it: <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">/kantan-analytics-agent</code> in Claude Code, or &ldquo;use the kantan-analytics-agent&rdquo; in Gemini CLI', 'kantan-analytics' ) ); ?></li>
                        </ol>
                        <p class="mt-3"><?php echo wp_kses_post( __( '<strong>Updating:</strong> the agent checks for a newer version on its own roughly once a week and updates itself — you don\'t have to do anything. To force a refresh without changing your API key, use <strong>Update agent file</strong> above (or just tell the agent &ldquo;check for an update&rdquo;).', 'kantan-analytics' ) ); ?></p>
                        <p class="mt-2"><?php echo wp_kses_post( __( '<strong>Multiple sites?</strong> Download once and reuse the same agent file everywhere. Each site only needs its own credentials — no per-site downloads.', 'kantan-analytics' ) ); ?></p>
                    </div>
                </details>

                <!-- Connect via MCP -->
                <?php
                $kantan_mcp_wp_ok      = version_compare( get_bloginfo( 'version' ), '6.9', '>=' );
                $kantan_mcp_adapter_ok = class_exists( '\WP\MCP\Core\McpAdapter' );
                $kantan_mcp_endpoint   = rest_url( 'kantan/mcp' );
                ?>
                <div class="mt-6 pt-5 border-t border-gray-100">
                    <div class="flex items-center gap-2">
                        <h3 class="text-sm font-bold text-gray-900"><?php esc_html_e('Connect via MCP', 'kantan-analytics'); ?></h3>
                        <?php if ( $kantan_mcp_wp_ok && $kantan_mcp_adapter_ok ) : ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"><?php esc_html_e('Active', 'kantan-analytics'); ?></span>
                        <?php else : ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600"><?php esc_html_e('Setup needed', 'kantan-analytics'); ?></span>
                        <?php endif; ?>
                    </div>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Exposes your analytics as typed, read-only tools for Claude Code and any MCP client. The agent above uses them automatically once connected — and if Kantan SEO is active, its tools share the same connection.', 'kantan-analytics'); ?></p>

                    <?php if ( ! $kantan_mcp_wp_ok ) : ?>
                        <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 mt-3 text-sm text-amber-800">
                            <?php printf( esc_html__( 'MCP requires WordPress 6.9 or newer — this site runs %s. Everything else keeps working; update WordPress to enable MCP.', 'kantan-analytics' ), esc_html( get_bloginfo( 'version' ) ) ); ?>
                        </div>
                    <?php elseif ( ! $kantan_mcp_adapter_ok ) : ?>
                        <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 mt-3 text-sm text-amber-800">
                            <?php echo wp_kses_post( __( 'One step left: install the free <a href="https://github.com/WordPress/mcp-adapter/releases/latest" target="_blank" rel="noopener" class="underline">MCP Adapter</a> plugin — download <code class="bg-amber-100 px-1.5 py-0.5 rounded text-xs">mcp-adapter.zip</code> from the WordPress GitHub releases, upload it under <strong>Plugins → Add New → Upload Plugin</strong>, and activate it. This card updates once it\'s active.', 'kantan-analytics' ) ); ?>
                        </div>
                    <?php else : ?>
                        <p class="mt-3 text-sm text-gray-600"><?php esc_html_e('MCP endpoint:', 'kantan-analytics'); ?> <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs"><?php echo esc_html( $kantan_mcp_endpoint ); ?></code></p>
                        <p class="mt-2 text-sm text-gray-600"><?php echo wp_kses_post( __( 'Connect Claude Code with one command — it reuses the same <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">KANTAN_APP_PASSWORD</code> from the agent setup above:', 'kantan-analytics' ) ); ?></p>
                        <pre class="mt-2 bg-gray-900 text-gray-100 rounded-lg p-3 text-xs overflow-x-auto"><code>claude mcp add kantan --transport http "<?php echo esc_html( $kantan_mcp_endpoint ); ?>" \
  --header "Authorization: Basic $(printf %s "$KANTAN_APP_PASSWORD" | base64)"</code></pre>
                        <p class="mt-2 text-xs text-gray-400"><?php esc_html_e('Read-only by design: agents can read data through MCP, never change settings or content. Other MCP clients connect with the same URL and Authorization header.', 'kantan-analytics'); ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Excluded IPs -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-6">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Excluded IP Addresses', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Exclude specific IP addresses from all tracking (visits, clicks, and conversions). Use this to filter out your own traffic. Supports individual IPs and CIDR notation (e.g., 10.0.0.0/24).', 'kantan-analytics'); ?></p>
                </div>

                <div id="kantan-excluded-ips">
                    <div class="mb-3 text-sm text-gray-500"><?php esc_html_e('Your current IP:', 'kantan-analytics'); ?> <code id="kantan-current-ip" class="bg-gray-100 px-2 py-0.5 rounded text-gray-700">loading...</code>
                        <button type="button" id="kantan-add-my-ip" class="ml-2 text-blue-600 hover:text-blue-800 text-sm font-medium"><?php esc_html_e('+ Add My IP', 'kantan-analytics'); ?></button>
                        <div id="kantan-ip-local-note" class="mt-1 text-xs text-gray-500 hidden">
                            <?php echo wp_kses_post( __( 'This is a local/private address — your site is likely behind a proxy or you\'re on a local network, so this isn\'t the address visitors are seen as. To find the external IP you browse from, visit <a href="https://whatismyipaddress.com/" target="_blank" rel="noopener" class="text-blue-600 underline">whatismyipaddress.com</a>.', 'kantan-analytics' ) ); ?>
                        </div>
                    </div>

                    <div id="kantan-ip-list" class="space-y-2 mb-4">
                        <!-- Rows injected by JS -->
                    </div>

                    <button type="button" id="kantan-ip-add"
                        class="inline-flex items-center gap-2 px-4 py-2 bg-white border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        <?php esc_html_e('Add IP Address', 'kantan-analytics'); ?>
                    </button>

                    <div class="mt-6 flex items-center gap-3">
                        <button type="button" id="kantan-ip-save"
                            class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                            <?php esc_html_e('Save Changes', 'kantan-analytics'); ?>
                        </button>
                        <span id="kantan-ip-status" class="text-sm text-gray-500"></span>
                    </div>
                </div>
            </div>

            </div><!-- /top row -->

            <!-- Bot / forged-traffic filtering -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-4">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Filter bot traffic', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Exclude suspected bots — sessions that bounce in under two seconds with no engagement — from your visit counts, bounce rate, duration, and sources. Nothing is deleted; turn this off any time to audit the raw data.', 'kantan-analytics'); ?></p>
                </div>
                <label class="inline-flex items-center gap-3 cursor-pointer">
                    <input type="checkbox" id="kantan-botfilter-toggle" <?php checked(kantan_bot_filter_enabled()); ?>
                        class="h-5 w-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                    <span class="text-sm font-medium text-gray-700"><?php esc_html_e('Exclude suspected bots from analytics', 'kantan-analytics'); ?></span>
                </label>
                <span id="kantan-botfilter-status" class="ml-3 text-sm text-gray-500"></span>
            </div>

            <?php ob_start(); ?>
            (function() {
                var toggle = document.getElementById('kantan-botfilter-toggle');
                var bfStatus = document.getElementById('kantan-botfilter-status');
                if (toggle) {
                    toggle.addEventListener('change', function() {
                        bfStatus.textContent = '<?php echo esc_js( __( 'Saving…', 'kantan-analytics' ) ); ?>';
                        fetch('<?php echo esc_url(rest_url('kantan/v1/bot-filter')); ?>', {
                            method: 'PUT',
                            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>' },
                            body: JSON.stringify({ enabled: toggle.checked })
                        })
                        .then(function(r) { return r.json(); })
                        .then(function() {
                            bfStatus.textContent = '<?php echo esc_js( __( 'Saved — reload to see updated metrics.', 'kantan-analytics' ) ); ?>';
                        })
                        .catch(function() {
                            bfStatus.textContent = '<?php echo esc_js( __( 'Could not save. Please try again.', 'kantan-analytics' ) ); ?>';
                        });
                    });
                }
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <?php ob_start(); ?>
            (function() {
                var ips = <?php echo json_encode(get_option('kantan_excluded_ips', array())); ?>;
                var list = document.getElementById('kantan-ip-list');
                var addBtn = document.getElementById('kantan-ip-add');
                var saveBtn = document.getElementById('kantan-ip-save');
                var status = document.getElementById('kantan-ip-status');
                var currentIpEl = document.getElementById('kantan-current-ip');
                var addMyIpBtn = document.getElementById('kantan-add-my-ip');

                function isLocalIp(ip) {
                    if (!ip) return false;
                    ip = ip.toLowerCase();
                    if (ip === '::1' || ip === 'localhost') return true;
                    // IPv6 link-local (fe80:) and unique-local (fc/fd).
                    if (ip.indexOf('fe80:') === 0 || ip.indexOf('fc') === 0 || ip.indexOf('fd') === 0) return true;
                    // IPv4 loopback / private / link-local ranges.
                    return /^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2[0-9]|3[01])\.)/.test(ip);
                }

                // Fetch current IP
                fetch('<?php echo esc_url(rest_url('kantan/v1/excluded-ips')); ?>', {
                    headers: { 'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>' }
                })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.current_ip) {
                        currentIpEl.textContent = data.current_ip;
                        if (isLocalIp(data.current_ip)) {
                            var note = document.getElementById('kantan-ip-local-note');
                            if (note) note.classList.remove('hidden');
                        }
                    }
                });

                function esc(s) {
                    var d = document.createElement('div');
                    d.textContent = (s == null ? '' : s);
                    return d.innerHTML.replace(/"/g, '&quot;');
                }

                function renderRow(ip, index) {
                    var div = document.createElement('div');
                    div.className = 'flex items-center gap-3';
                    div.setAttribute('data-index', index);
                    div.innerHTML = ''
                        + '<input type="text" data-field="ip" value="' + esc(ip || '') + '"'
                        + '  placeholder="<?php echo esc_js( __( 'e.g. 192.168.1.1 or 10.0.0.0/24', 'kantan-analytics' ) ); ?>"'
                        + '  class="flex-1 max-w-md px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 font-mono">'
                        + '<button type="button" class="kantan-ip-remove p-2 text-gray-400 hover:text-red-500 transition">'
                        + '  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>'
                        + '</button>';
                    return div;
                }

                function renderAll() {
                    list.innerHTML = '';
                    if (ips.length === 0) {
                        list.innerHTML = '<p class="text-gray-400 text-sm py-2"><?php echo esc_js( __( 'No IPs excluded. Your visits are being tracked.', 'kantan-analytics' ) ); ?></p>';
                        return;
                    }
                    ips.forEach(function(ip, i) {
                        list.appendChild(renderRow(ip, i));
                    });
                }

                function collectIps() {
                    var rows = list.querySelectorAll('[data-index]');
                    var result = [];
                    rows.forEach(function(row) {
                        var val = row.querySelector('[data-field="ip"]').value.trim();
                        if (val) result.push(val);
                    });
                    return result;
                }

                addBtn.addEventListener('click', function() {
                    ips.push('');
                    renderAll();
                    var inputs = list.querySelectorAll('[data-field="ip"]');
                    if (inputs.length) inputs[inputs.length - 1].focus();
                });

                addMyIpBtn.addEventListener('click', function() {
                    var myIp = currentIpEl.textContent;
                    if (myIp && myIp !== 'loading...') {
                        // Check if already in list
                        if (ips.indexOf(myIp) === -1) {
                            ips.push(myIp);
                            renderAll();
                        }
                    }
                });

                list.addEventListener('click', function(e) {
                    var btn = e.target.closest('.kantan-ip-remove');
                    if (!btn) return;
                    var row = btn.closest('[data-index]');
                    var idx = parseInt(row.getAttribute('data-index'));
                    ips.splice(idx, 1);
                    renderAll();
                });

                saveBtn.addEventListener('click', function() {
                    var data = collectIps();
                    status.textContent = '<?php echo esc_js( __( 'Saving...', 'kantan-analytics' ) ); ?>';
                    saveBtn.disabled = true;

                    fetch('<?php echo esc_url(rest_url('kantan/v1/excluded-ips')); ?>', {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                        },
                        body: JSON.stringify({ ips: data })
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(resp) {
                        if (resp.updated) {
                            ips = resp.ips;
                            status.textContent = '<?php echo esc_js( __( 'Saved!', 'kantan-analytics' ) ); ?>';
                            status.className = 'text-sm text-green-600';
                            renderAll();
                        } else {
                            status.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (resp.message || '<?php echo esc_js( __( 'Unknown', 'kantan-analytics' ) ); ?>');
                            status.className = 'text-sm text-red-600';
                        }
                        saveBtn.disabled = false;
                        setTimeout(function() { status.textContent = ''; status.className = 'text-sm text-gray-500'; }, 3000);
                    })
                    .catch(function(err) {
                        status.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message;
                        status.className = 'text-sm text-red-600';
                        saveBtn.disabled = false;
                    });
                });

                renderAll();
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <!-- Conversion Links -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-6">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Conversion Links', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Track clicks to external booking systems, shops, or any outbound link as conversions. When a visitor clicks a link matching one of these domains, it\'s recorded as a conversion with the button text, page location, and traffic source.', 'kantan-analytics'); ?></p>
                </div>

                <div id="kantan-conversion-links">
                    <div id="kantan-cl-list" class="space-y-3 mb-4">
                        <!-- Rows injected by JS -->
                    </div>

                    <button type="button" id="kantan-cl-add"
                        class="inline-flex items-center gap-2 px-4 py-2 bg-white border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        <?php esc_html_e('Add Conversion Link', 'kantan-analytics'); ?>
                    </button>

                    <div class="mt-6 flex items-center gap-3">
                        <button type="button" id="kantan-cl-save"
                            class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                            <?php esc_html_e('Save Changes', 'kantan-analytics'); ?>
                        </button>
                        <span id="kantan-cl-status" class="text-sm text-gray-500"></span>
                    </div>

                    <details class="mt-6 text-sm text-gray-500">
                        <summary class="cursor-pointer text-gray-600 hover:text-gray-800 font-medium"><?php esc_html_e('How conversion links work', 'kantan-analytics'); ?></summary>
                        <div class="mt-2 space-y-2 pl-1">
                            <p><?php esc_html_e('When a visitor clicks a link matching a configured domain:', 'kantan-analytics'); ?></p>
                            <ol class="list-decimal ml-5 space-y-1">
                                <li><?php echo wp_kses_post( __( 'A <strong class="text-gray-700">conversion event</strong> is recorded with the button text and page section', 'kantan-analytics' ) ); ?></li>
                                <li><?php echo wp_kses_post( __( 'The conversion is tied to the visitor\'s <strong class="text-gray-700">session and traffic source</strong>', 'kantan-analytics' ) ); ?></li>
                                <li><?php echo wp_kses_post( __( 'If UTM is enabled, <strong class="text-gray-700">UTM parameters</strong> are appended to the outbound URL', 'kantan-analytics' ) ); ?></li>
                            </ol>
                        </div>
                    </details>
                </div>
            </div>

            <!-- Business Profile (agent ground truth) -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-4">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Business Profile', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php echo wp_kses_post( __( 'The canonical facts your Kantan AI agents treat as <strong>ground truth</strong> when writing or rewriting content — basics, hours, offerings, brand voice, and claims to make or avoid. Agents read this before generating anything, so keep it accurate.', 'kantan-analytics' ) ); ?> <span id="kantan-profile-updated" class="text-gray-400"></span></p>
                </div>
                <textarea id="kantan-profile-content" rows="16" spellcheck="false" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-xs font-mono leading-relaxed"></textarea>
                <div class="mt-3 flex items-center gap-3">
                    <button type="button" id="kantan-profile-save" class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition"><?php esc_html_e('Save profile', 'kantan-analytics'); ?></button>
                    <span id="kantan-profile-status" class="text-sm text-gray-500"></span>
                </div>
                <p class="text-xs text-gray-400 mt-3"><?php echo wp_kses_post( __( 'Tip: let the agent draft it — run the <strong>&ldquo;Draft my business profile&rdquo;</strong> prompt in your Kantan agent, review it, and it saves here. Markdown.', 'kantan-analytics' ) ); ?></p>
            </div>
            <?php ob_start(); ?>
            (function () {
                var REST = '<?php echo esc_url(rest_url('kantan/v1')); ?>', NONCE = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
                var ta = document.getElementById('kantan-profile-content'), save = document.getElementById('kantan-profile-save'),
                    status = document.getElementById('kantan-profile-status'), updated = document.getElementById('kantan-profile-updated');
                if (!ta) { return; }
                function setStatus(m, c) { status.textContent = m; status.className = 'text-sm ' + (c || 'text-gray-500'); }
                function setUpdated(t) { updated.textContent = t ? ('<?php echo esc_js( __( '· last updated ', 'kantan-analytics' ) ); ?>' + t) : '<?php echo esc_js( __( '· not set yet — fill this in or have your agent draft it.', 'kantan-analytics' ) ); ?>'; }
                fetch(REST + '/profile', { credentials: 'same-origin', headers: { 'X-WP-Nonce': NONCE } })
                    .then(function (r) { return r.json(); })
                    .then(function (c) { if (!c) { return; } ta.value = (c.content && c.content.length) ? c.content : (c.default || ''); setUpdated(c.updated_at); })
                    .catch(function () {});
                save.addEventListener('click', function () {
                    save.disabled = true; setStatus('<?php echo esc_js( __( 'Saving…', 'kantan-analytics' ) ); ?>', 'text-blue-600');
                    fetch(REST + '/profile', { method: 'PUT', credentials: 'same-origin', headers: { 'X-WP-Nonce': NONCE, 'Content-Type': 'application/json' }, body: JSON.stringify({ content: ta.value }) })
                        .then(function (r) { return r.json(); })
                        .then(function (res) { save.disabled = false; if (res && res.saved) { setStatus('<?php echo esc_js( __( 'Saved.', 'kantan-analytics' ) ); ?>', 'text-green-600'); setUpdated(res.updated_at); } else { setStatus('<?php echo esc_js( __( 'Save failed.', 'kantan-analytics' ) ); ?>', 'text-red-600'); } })
                        .catch(function () { save.disabled = false; setStatus('<?php echo esc_js( __( 'Save failed.', 'kantan-analytics' ) ); ?>', 'text-red-600'); });
                });
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <!-- Attribution Webhook / CRM -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-4">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Attribution Webhook / CRM', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Send every conversion — with its first-party campaign + journey attribution — to a webhook your email/CRM tool (HubSpot, GoHighLevel, Salesforce, Zapier, Make…) can receive. Keyed by an anonymous visitor id; no personal data leaves your site.', 'kantan-analytics'); ?></p>
                </div>
                <div class="space-y-3 max-w-2xl">
                    <label class="flex items-center gap-2 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-wh-enabled" class="accent-blue-600 w-4 h-4" /> <?php esc_html_e('Enable conversion webhook', 'kantan-analytics'); ?>
                    </label>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1"><?php esc_html_e('Webhook URL', 'kantan-analytics'); ?></label>
                        <input type="url" id="kantan-wh-url" placeholder="https://hooks.zapier.com/…" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1"><?php esc_html_e('Signing secret', 'kantan-analytics'); ?> <span class="text-gray-400"><?php esc_html_e('(optional, recommended)', 'kantan-analytics'); ?></span></label>
                        <input type="password" id="kantan-wh-secret" placeholder="••••••••" autocomplete="off" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
                        <p id="kantan-wh-secret-state" class="text-xs text-gray-400 mt-1"></p>
                        <p class="text-xs text-gray-400 mt-1"><?php echo wp_kses_post( __( 'If set, each request includes an <code class="bg-gray-100 px-1 rounded">X-Kantan-Signature: sha256=…</code> HMAC of the body, so your receiver can verify it.', 'kantan-analytics' ) ); ?></p>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1"><?php esc_html_e('Passthrough params to capture', 'kantan-analytics'); ?></label>
                        <textarea id="kantan-wh-params" rows="3" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-xs font-mono"></textarea>
                        <p class="text-xs text-gray-400 mt-1"><?php echo wp_kses_post( __( 'Inbound URL params (ad-click &amp; CRM contact ids) captured and added to the payload\'s <code class="bg-gray-100 px-1 rounded">attribution.passthrough</code>. Comma-separated; case-insensitive.', 'kantan-analytics' ) ); ?></p>
                    </div>
                    <div class="flex items-center gap-3 pt-1">
                        <button type="button" id="kantan-wh-save" class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition"><?php esc_html_e('Save', 'kantan-analytics'); ?></button>
                        <button type="button" id="kantan-wh-test" class="px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50 transition"><?php esc_html_e('Send test', 'kantan-analytics'); ?></button>
                        <span id="kantan-wh-status" class="text-sm text-gray-500"></span>
                    </div>
                    <div id="kantan-wh-recent" class="text-xs text-gray-500"></div>

                    <details class="mt-2 text-sm text-gray-500">
                        <summary class="cursor-pointer text-gray-600 hover:text-gray-800 font-medium"><?php esc_html_e('Connect your CRM (the join key)', 'kantan-analytics'); ?></summary>
                        <div class="mt-3 space-y-2 pl-1">
                            <p><?php echo wp_kses_post( __( 'Kantan already injects a hidden <code class="bg-gray-100 px-1 rounded">kantan_visitor_id</code> field into your forms. Map that field to a custom field on the contact, then match the webhook to the contact by it.', 'kantan-analytics' ) ); ?></p>
                            <ul class="list-disc ml-5 space-y-1">
                                <li><?php echo wp_kses_post( __( '<strong>Zapier / Make:</strong> Catch Hook → upsert contact, match on the <code class="bg-gray-100 px-1 rounded">visitor_id</code> custom field; map <code class="bg-gray-100 px-1 rounded">attribution.utm.*</code> to fields.', 'kantan-analytics' ) ); ?></li>
                                <li><?php echo wp_kses_post( __( '<strong>GoHighLevel:</strong> Inbound Webhook trigger → update contact by the visitor-id field (or <code class="bg-gray-100 px-1 rounded">passthrough.contact_id</code> if the link carried GHL\'s id).', 'kantan-analytics' ) ); ?></li>
                                <li><?php echo wp_kses_post( __( '<strong>HubSpot:</strong> Workflow webhook / custom-coded action (or via Zapier) → store visitor_id on the contact, set campaign/source properties.', 'kantan-analytics' ) ); ?></li>
                                <li><?php echo wp_kses_post( __( '<strong>Salesforce:</strong> Inbound via Zapier/Make or a Flow HTTP callout → match Lead/Contact by the visitor-id field.', 'kantan-analytics' ) ); ?></li>
                            </ul>
                            <p class="text-gray-400"><?php echo wp_kses_post( __( 'Payload (JSON): <code class="bg-gray-100 px-1 rounded">visitor_id</code>, <code class="bg-gray-100 px-1 rounded">type</code>, <code class="bg-gray-100 px-1 rounded">attribution.utm</code>, <code class="bg-gray-100 px-1 rounded">attribution.passthrough</code>, <code class="bg-gray-100 px-1 rounded">journey[]</code> — no name or email.', 'kantan-analytics' ) ); ?></p>
                        </div>
                    </details>
                </div>
            </div>
            <?php ob_start(); ?>
            (function () {
                var REST = '<?php echo esc_url(rest_url('kantan/v1')); ?>', NONCE = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
                var en = document.getElementById('kantan-wh-enabled'), url = document.getElementById('kantan-wh-url'),
                    secret = document.getElementById('kantan-wh-secret'), secretState = document.getElementById('kantan-wh-secret-state'),
                    paramsEl = document.getElementById('kantan-wh-params'), save = document.getElementById('kantan-wh-save'),
                    test = document.getElementById('kantan-wh-test'), status = document.getElementById('kantan-wh-status'), recent = document.getElementById('kantan-wh-recent');
                if (!save) { return; }
                function setStatus(m, c) { status.textContent = m; status.className = 'text-sm ' + (c || 'text-gray-500'); }
                function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }
                function renderRecent(list) {
                    if (!list || !list.length) { recent.innerHTML = ''; return; }
                    recent.innerHTML = '<div class="mt-1 mb-0.5 text-gray-400"><?php echo esc_js( __( 'Recent deliveries:', 'kantan-analytics' ) ); ?></div>' + list.slice(0, 6).map(function (r) {
                        var ok = (r.status === 'sent' || /^2\d\d$/.test(r.status));
                        return '<div class="' + (ok ? 'text-gray-500' : 'text-red-500') + '">' + esc(r.ts) + ' · ' + esc(r.type) + ' · ' + esc(r.status) + '</div>';
                    }).join('');
                }
                function apply(c) {
                    if (!c) { return; }
                    en.checked = !!c.enabled; url.value = c.url || ''; paramsEl.value = c.passthrough_params || '';
                    secretState.textContent = c.secret_set ? '<?php echo esc_js( __( 'A signing secret is saved. Leave blank to keep it; type a new one to replace it.', 'kantan-analytics' ) ); ?>' : '<?php echo esc_js( __( 'No signing secret set.', 'kantan-analytics' ) ); ?>';
                    renderRecent(c.recent);
                }
                fetch(REST + '/webhook/config', { credentials: 'same-origin', headers: { 'X-WP-Nonce': NONCE } }).then(function (r) { return r.json(); }).then(apply).catch(function () {});
                function payload() { var p = { enabled: en.checked, url: url.value.trim(), passthrough_params: paramsEl.value.trim() }; if (secret.value.trim() !== '') { p.secret = secret.value.trim(); } return p; }
                save.addEventListener('click', function () {
                    save.disabled = true; setStatus('<?php echo esc_js( __( 'Saving…', 'kantan-analytics' ) ); ?>', 'text-blue-600');
                    fetch(REST + '/webhook/config', { method: 'PUT', credentials: 'same-origin', headers: { 'X-WP-Nonce': NONCE, 'Content-Type': 'application/json' }, body: JSON.stringify(payload()) })
                        .then(function (r) { return r.json(); })
                        .then(function (res) { save.disabled = false; if (res && res.saved) { setStatus('<?php echo esc_js( __( 'Saved.', 'kantan-analytics' ) ); ?>', 'text-green-600'); secret.value = ''; apply(res.config); } else { setStatus('<?php echo esc_js( __( 'Save failed.', 'kantan-analytics' ) ); ?>', 'text-red-600'); } })
                        .catch(function () { save.disabled = false; setStatus('<?php echo esc_js( __( 'Save failed.', 'kantan-analytics' ) ); ?>', 'text-red-600'); });
                });
                test.addEventListener('click', function () {
                    test.disabled = true; setStatus('<?php echo esc_js( __( 'Sending test…', 'kantan-analytics' ) ); ?>', 'text-blue-600');
                    fetch(REST + '/webhook/test', { method: 'POST', credentials: 'same-origin', headers: { 'X-WP-Nonce': NONCE, 'Content-Type': 'application/json' }, body: '{}' })
                        .then(function (r) { return r.json(); })
                        .then(function (res) {
                            test.disabled = false;
                            if (res && res.ok) { setStatus('✓ ' + '<?php echo esc_js( __( 'Sent', 'kantan-analytics' ) ); ?>' + (res.code ? ' (HTTP ' + res.code + ')' : '') + '.', 'text-green-600'); }
                            else { var msg = (res && res.error) ? res.error : ('HTTP ' + (res && res.code ? res.code : '?')); setStatus('✗ ' + msg, 'text-red-600'); }
                            if (res && res.config) { renderRecent(res.config.recent); }
                        })
                        .catch(function () { test.disabled = false; setStatus('✗ Test failed', 'text-red-600'); });
                });
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <!-- Data Retention & Storage -->
            <?php $kantan_sqlite = function_exists('kantan_sqlite_health') ? kantan_sqlite_health() : array('available' => false); ?>
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-6">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Data Retention & Storage', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Raw per-event detail (sessions, clicks, pageviews) lives in your WordPress database and is pruned on a rolling window. Daily aggregates, visitor profiles, and conversion history are kept indefinitely in a lightweight SQLite file so long-term trends and attribution survive.', 'kantan-analytics'); ?></p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label for="kantan-retention-days" class="block text-sm font-medium text-gray-700 mb-2"><?php esc_html_e('Raw data retention (MySQL)', 'kantan-analytics'); ?></label>
                        <select id="kantan-retention-days" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="30"><?php esc_html_e('30 days', 'kantan-analytics'); ?></option>
                            <option value="60"><?php esc_html_e('60 days', 'kantan-analytics'); ?></option>
                            <option value="90" selected><?php esc_html_e('90 days (recommended)', 'kantan-analytics'); ?></option>
                            <option value="180"><?php esc_html_e('180 days', 'kantan-analytics'); ?></option>
                            <option value="365"><?php esc_html_e('365 days', 'kantan-analytics'); ?></option>
                            <option value="730"><?php esc_html_e('2 years', 'kantan-analytics'); ?></option>
                        </select>
                        <p class="text-xs text-gray-500 mt-2"><?php esc_html_e('After this window, heatmaps and journey replays are lost. Daily totals, visitor profiles, and conversions are preserved forever in SQLite regardless of this setting.', 'kantan-analytics'); ?></p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2"><?php esc_html_e('Long-term storage (SQLite)', 'kantan-analytics'); ?></label>
                        <div class="bg-gray-50 rounded-lg p-3 text-sm space-y-1">
                            <?php if (!$kantan_sqlite['available']): ?>
                                <div class="text-red-600"><?php esc_html_e('SQLite3 PHP extension not available on this host. Install php-sqlite3 to enable long-term storage.', 'kantan-analytics'); ?></div>
                            <?php else: ?>
                                <div class="text-gray-700"><?php esc_html_e('Status:', 'kantan-analytics'); ?> <span class="text-green-600 font-medium"><?php esc_html_e('Active', 'kantan-analytics'); ?></span></div>
                                <div class="text-gray-500"><?php esc_html_e('File size:', 'kantan-analytics'); ?> <code class="bg-white px-1.5 py-0.5 rounded border text-xs"><?php echo esc_html(size_format(intval($kantan_sqlite['size']))); ?></code></div>
                                <div class="text-gray-500"><?php esc_html_e('Visitors tracked:', 'kantan-analytics'); ?> <code class="bg-white px-1.5 py-0.5 rounded border text-xs"><?php echo intval($kantan_sqlite['visitor_count']); ?></code></div>
                                <div class="text-gray-500"><?php esc_html_e('Last aggregated:', 'kantan-analytics'); ?> <code class="bg-white px-1.5 py-0.5 rounded border text-xs"><?php echo $kantan_sqlite['last_aggregated_date'] ? esc_html($kantan_sqlite['last_aggregated_date']) : esc_html__('never — run now below', 'kantan-analytics'); ?></code></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="flex items-center gap-3">
                    <button type="button" id="kantan-retention-save"
                        class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                        <?php esc_html_e('Save Retention', 'kantan-analytics'); ?>
                    </button>
                    <?php if ($kantan_sqlite['available']): ?>
                    <button type="button" id="kantan-aggregate-now"
                        class="px-5 py-2 bg-white border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50 transition">
                        <?php esc_html_e('Run Aggregation Now', 'kantan-analytics'); ?>
                    </button>
                    <?php endif; ?>
                    <span id="kantan-retention-status" class="text-sm text-gray-500"></span>
                </div>
            </div>

            <?php ob_start(); ?>
            (function() {
                var nonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
                var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
                var sel = document.getElementById('kantan-retention-days');
                var saveBtn = document.getElementById('kantan-retention-save');
                var aggBtn = document.getElementById('kantan-aggregate-now');
                var status = document.getElementById('kantan-retention-status');

                function setStatus(msg, klass) {
                    status.textContent = msg;
                    status.className = 'text-sm ' + (klass || 'text-gray-500');
                    if (msg) setTimeout(function() { status.textContent = ''; status.className = 'text-sm text-gray-500'; }, 4000);
                }

                fetch(restBase + '/retention', { headers: { 'X-WP-Nonce': nonce }})
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        if (data && data.raw_retention_days) {
                            var opt = sel.querySelector('option[value="' + data.raw_retention_days + '"]');
                            if (opt) sel.value = data.raw_retention_days;
                        }
                    });

                saveBtn.addEventListener('click', function() {
                    saveBtn.disabled = true;
                    setStatus('<?php echo esc_js( __( 'Saving...', 'kantan-analytics' ) ); ?>', 'text-gray-500');
                    fetch(restBase + '/retention', {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                        body: JSON.stringify({ raw_retention_days: parseInt(sel.value, 10) })
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(resp) {
                        saveBtn.disabled = false;
                        if (resp && resp.updated) setStatus('<?php echo esc_js( __( 'Saved', 'kantan-analytics' ) ); ?>', 'text-green-600');
                        else setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (resp.message || '<?php echo esc_js( __( 'unknown', 'kantan-analytics' ) ); ?>'), 'text-red-600');
                    })
                    .catch(function(err) {
                        saveBtn.disabled = false;
                        setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message, 'text-red-600');
                    });
                });

                if (aggBtn) {
                    aggBtn.addEventListener('click', function() {
                        aggBtn.disabled = true;
                        setStatus('<?php echo esc_js( __( 'Running aggregation...', 'kantan-analytics' ) ); ?>', 'text-gray-500');
                        fetch(restBase + '/retention/aggregate-now', {
                            method: 'POST',
                            headers: { 'X-WP-Nonce': nonce }
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(resp) {
                            aggBtn.disabled = false;
                            if (resp && resp.triggered) {
                                var msg = '<?php echo esc_js( __( 'Processed %s day(s)', 'kantan-analytics' ) ); ?>'.replace('%s', (resp.days_processed || 0));
                                if (resp.last_date) msg += ' — ' + '<?php echo esc_js( __( 'up to', 'kantan-analytics' ) ); ?>' + ' ' + resp.last_date;
                                if (resp.skipped_reason) msg = '<?php echo esc_js( __( 'Skipped: ', 'kantan-analytics' ) ); ?>' + resp.skipped_reason;
                                setStatus(msg, 'text-green-600');
                            } else {
                                setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (resp.message || '<?php echo esc_js( __( 'unknown', 'kantan-analytics' ) ); ?>'), 'text-red-600');
                            }
                        })
                        .catch(function(err) {
                            aggBtn.disabled = false;
                            setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message, 'text-red-600');
                        });
                    });
                }
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <!-- Video Tracking -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-6">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Video Tracking', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Measures engagement for videos embedded on your pages — plays, watch time, and completion, per video, tied to visitor sessions. Provider scripts (YouTube / Vimeo) load only on pages that actually embed them.', 'kantan-analytics'); ?></p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-3 mb-6">
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-enabled" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span>
                            <span class="font-medium"><?php esc_html_e('Enable video tracking', 'kantan-analytics'); ?></span><br>
                            <span class="text-xs text-gray-500"><?php esc_html_e('Master switch. When off, no video data is collected at all.', 'kantan-analytics'); ?></span>
                        </span>
                    </label>
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-nocookie" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span>
                            <span class="font-medium"><?php esc_html_e('Privacy-enhanced YouTube', 'kantan-analytics'); ?></span><br>
                            <span class="text-xs text-gray-500"><?php esc_html_e('Rewrites YouTube embeds to youtube-nocookie.com so YouTube sets no tracking cookies.', 'kantan-analytics'); ?></span>
                        </span>
                    </label>
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-youtube" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span class="font-medium"><?php esc_html_e('Track YouTube embeds', 'kantan-analytics'); ?></span>
                    </label>
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-vimeo" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span class="font-medium"><?php esc_html_e('Track Vimeo embeds', 'kantan-analytics'); ?></span>
                    </label>
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-html5" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span class="font-medium"><?php esc_html_e('Track self-hosted videos', 'kantan-analytics'); ?></span>
                    </label>
                    <label class="flex items-start gap-3 text-sm text-gray-700">
                        <input type="checkbox" id="kantan-video-exclude-autoplay" class="mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        <span>
                            <span class="font-medium"><?php esc_html_e('Ignore muted autoplay videos', 'kantan-analytics'); ?></span><br>
                            <span class="text-xs text-gray-500"><?php esc_html_e('Background hero loops autoplay silently and would inflate your play rate.', 'kantan-analytics'); ?></span>
                        </span>
                    </label>
                </div>

                <div class="flex items-center gap-3">
                    <button type="button" id="kantan-video-save"
                        class="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                        <?php esc_html_e('Save Video Settings', 'kantan-analytics'); ?>
                    </button>
                    <span id="kantan-video-status" class="text-sm text-gray-500"></span>
                </div>
            </div>

            <?php ob_start(); ?>
            (function() {
                var nonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
                var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
                var saveBtn = document.getElementById('kantan-video-save');
                var status = document.getElementById('kantan-video-status');
                var fields = {
                    enabled: document.getElementById('kantan-video-enabled'),
                    youtube: document.getElementById('kantan-video-youtube'),
                    vimeo: document.getElementById('kantan-video-vimeo'),
                    html5: document.getElementById('kantan-video-html5'),
                    nocookie: document.getElementById('kantan-video-nocookie'),
                    exclude_autoplay: document.getElementById('kantan-video-exclude-autoplay')
                };

                function setStatus(msg, klass) {
                    status.textContent = msg;
                    status.className = 'text-sm ' + (klass || 'text-gray-500');
                    if (msg) setTimeout(function() { status.textContent = ''; status.className = 'text-sm text-gray-500'; }, 4000);
                }

                fetch(restBase + '/video-settings', { headers: { 'X-WP-Nonce': nonce }})
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        if (!data) return;
                        Object.keys(fields).forEach(function(key) {
                            if (typeof data[key] !== 'undefined') fields[key].checked = !!data[key];
                        });
                    });

                saveBtn.addEventListener('click', function() {
                    saveBtn.disabled = true;
                    setStatus('<?php echo esc_js( __( 'Saving...', 'kantan-analytics' ) ); ?>', 'text-gray-500');
                    var body = {};
                    Object.keys(fields).forEach(function(key) { body[key] = fields[key].checked; });
                    fetch(restBase + '/video-settings', {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                        body: JSON.stringify(body)
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(resp) {
                        saveBtn.disabled = false;
                        if (resp && resp.updated) setStatus('<?php echo esc_js( __( 'Saved', 'kantan-analytics' ) ); ?>', 'text-green-600');
                        else setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + ((resp && resp.message) || '<?php echo esc_js( __( 'unknown', 'kantan-analytics' ) ); ?>'), 'text-red-600');
                    })
                    .catch(function(err) {
                        saveBtn.disabled = false;
                        setStatus('<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message, 'text-red-600');
                    });
                });
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <!-- Support & Bug Reports -->
            <?php $support_url = function_exists('kantan_support_mailto') ? kantan_support_mailto('Kantan Analytics', KANTAN_ANALYTICS_VERSION, array(
                'Kantan SEO' => defined('KANTAN_SEO_VERSION') ? KANTAN_SEO_VERSION : 'not active',
            )) : 'mailto:hello@trykantan.com'; ?>
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <div class="mb-4">
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('Support & Bug Reports', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-500 text-sm mt-1"><?php esc_html_e('Hit a bug or need a hand? Email us — the link pre-fills your version and environment so we can help faster.', 'kantan-analytics'); ?></p>
                </div>
                <a href="<?php echo esc_url($support_url); ?>"
                    class="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white no-underline hover:text-white hover:no-underline rounded-lg text-sm font-medium hover:bg-blue-700 transition">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                    <?php esc_html_e('Email Support', 'kantan-analytics'); ?>
                </a>
                <p class="text-gray-400 text-xs mt-3"><?php echo wp_kses_post( __( 'Or write to <a href="mailto:hello@trykantan.com" class="text-blue-600">hello@trykantan.com</a> directly.', 'kantan-analytics' ) ); ?></p>
            </div>

            <!-- Agent Credentials Modal -->
            <div id="kantan-agent-modal" class="fixed inset-0 z-[99999] hidden" style="margin:0!important;">
                <div class="absolute inset-0 bg-black/50" id="kantan-agent-modal-backdrop"></div>
                <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl max-w-lg w-full p-6" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('Agent Credentials', 'kantan-analytics'); ?></h3>
                        <button type="button" id="kantan-agent-modal-close" class="text-gray-400 hover:text-gray-600 p-1">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>
                    </div>
                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 mb-4">
                        <p class="text-amber-800 text-sm"><?php echo wp_kses_post( __( '<strong>Important:</strong> This password is shown only once &mdash; copy it now.', 'kantan-analytics' ) ); ?></p>
                        <p class="text-amber-800 text-sm mt-2"><?php echo wp_kses_post( __( 'It is a WordPress Application Password with the <strong>full API access of your account</strong> (not read-only). Treat it like a password: keep it out of version control and shared chats. Revoke any time under <strong>Users &rarr; Profile &rarr; Application Passwords</strong>.', 'kantan-analytics' ) ); ?></p>
                    </div>
                    <p class="text-gray-600 text-sm mb-3"><?php echo wp_kses_post( __( 'Add these to your <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.zshrc</code>, <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.bashrc</code>, or project <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">.env</code> file:', 'kantan-analytics' ) ); ?></p>
                    <div class="bg-gray-900 rounded-lg p-4 font-mono text-sm text-green-400 relative overflow-x-auto">
                        <button type="button" id="kantan-agent-copy" class="absolute top-2 right-2 text-gray-400 hover:text-white transition" title="<?php esc_attr_e('Copy', 'kantan-analytics'); ?>">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                        </button>
                        <pre id="kantan-agent-env-vars" style="white-space:pre-wrap;word-break:break-all;"></pre>
                    </div>
                    <p class="text-gray-400 text-xs mt-3"><?php echo wp_kses_post( __( 'Place the downloaded <code>.md</code> file in <code>.claude/agents/</code> (Claude Code) or <code>.gemini/agents/</code> (Gemini CLI).', 'kantan-analytics' ) ); ?></p>

                    <?php if (function_exists('kantan_analytics_starter_prompts')): ?>
                    <div class="mt-5">
                        <p class="text-sm font-semibold text-gray-700 mb-2"><?php esc_html_e('Try these prompts', 'kantan-analytics'); ?></p>
                        <div class="space-y-2">
                            <?php foreach (kantan_analytics_starter_prompts() as $sp): ?>
                            <div class="border border-gray-200 rounded-lg p-3 flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <p class="text-sm font-medium text-gray-900"><?php echo esc_html($sp['title']); ?></p>
                                    <p class="text-xs text-gray-500 mt-0.5"><?php echo esc_html($sp['prompt']); ?></p>
                                </div>
                                <button type="button" class="kantan-prompt-copy flex-shrink-0 text-xs px-2 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition" data-prompt="<?php echo esc_attr($sp['prompt']); ?>"><?php esc_html_e('Copy', 'kantan-analytics'); ?></button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php ob_start(); ?>
            (function() {
                // Copy-to-clipboard for any starter-prompt button (delegated).
                document.addEventListener('click', function(e) {
                    var b = e.target.closest('.kantan-prompt-copy');
                    if (!b) return;
                    var text = b.getAttribute('data-prompt') || '';
                    var done = function() { var o = b.textContent; b.textContent = '<?php echo esc_js( __( 'Copied!', 'kantan-analytics' ) ); ?>'; setTimeout(function() { b.textContent = o; }, 1500); };
                    if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(done).catch(done); }
                    else { done(); }
                });
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

            <?php ob_start(); ?>
            (function() {
                'use strict';
                var agentBtn = document.getElementById('kantan-download-agent');
                var agentStatus = document.getElementById('kantan-agent-status');
                var agentModal = document.getElementById('kantan-agent-modal');
                var agentBackdrop = document.getElementById('kantan-agent-modal-backdrop');
                var agentClose = document.getElementById('kantan-agent-modal-close');
                var agentCopy = document.getElementById('kantan-agent-copy');
                var agentEnv = document.getElementById('kantan-agent-env-vars');
                var nonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
                var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';

                function closeModal() { agentModal.classList.add('hidden'); }
                if (agentClose) agentClose.addEventListener('click', closeModal);
                if (agentBackdrop) agentBackdrop.addEventListener('click', closeModal);
                document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeModal(); });

                function downloadBlob(content, filename) {
                    var blob = new Blob([content], { type: 'text/markdown' });
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url; a.download = filename;
                    document.body.appendChild(a); a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }

                if (agentBtn) {
                    agentBtn.addEventListener('click', function() {
                        agentBtn.disabled = true;
                        agentStatus.textContent = '<?php echo esc_js( __( 'Scanning site...', 'kantan-analytics' ) ); ?>';
                        agentStatus.className = 'text-sm text-blue-600';

                        // Step 1: Scan site
                        fetch(restBase + '/agent/scan', {
                            method: 'POST',
                            headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' }
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(scan) {
                            // Show brief summary
                            var builders = scan.builders || {};
                            var summary = [];
                            for (var b in builders) {
                                if (builders[b].active && builders[b].page_count > 0) {
                                    var label = b === 'acf' ? 'ACF' : b === 'beaver_builder' ? 'Beaver' : b === 'wpbakery' ? 'WPBakery' : b.charAt(0).toUpperCase() + b.slice(1);
                                    summary.push(label + ' (' + builders[b].page_count + ')');
                                }
                            }
                            agentStatus.textContent = '<?php echo esc_js( __( 'Detected:', 'kantan-analytics' ) ); ?>' + ' ' + (summary.join(', ') || 'Gutenberg') + ' — ' + '<?php echo esc_js( __( 'Generating agent...', 'kantan-analytics' ) ); ?>';

                            // Step 2: Generate agent (analytics is always recommend mode)
                            return fetch(restBase + '/agent/generate', {
                                method: 'POST',
                                headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' },
                                body: JSON.stringify({ plugin: 'analytics', mode: 'recommend' })
                            });
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(data) {
                            if (data.agent_md) {
                                downloadBlob(data.agent_md, data.filename);
                                agentEnv.textContent = 'export KANTAN_SITE_URL="' + data.site_url + '"\nexport KANTAN_APP_PASSWORD="' + data.username + ':' + data.app_password + '"';
                                agentModal.classList.remove('hidden');
                                agentStatus.textContent = '<?php echo esc_js( __( 'Downloaded!', 'kantan-analytics' ) ); ?>';
                                agentStatus.className = 'text-sm text-green-600';
                            } else {
                                agentStatus.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (data.message || '<?php echo esc_js( __( 'Unknown error', 'kantan-analytics' ) ); ?>');
                                agentStatus.className = 'text-sm text-red-600';
                            }
                            agentBtn.disabled = false;
                        })
                        .catch(function(err) {
                            agentStatus.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message;
                            agentStatus.className = 'text-sm text-red-600';
                            agentBtn.disabled = false;
                        });
                    });
                }

                // "Update agent file" — fetches the latest .md without minting a
                // new Application Password, so an existing install keeps its key.
                var updateBtn = document.getElementById('kantan-update-agent');
                if (updateBtn) {
                    updateBtn.addEventListener('click', function() {
                        updateBtn.disabled = true;
                        agentStatus.textContent = '<?php echo esc_js( __( 'Fetching latest agent…', 'kantan-analytics' ) ); ?>';
                        agentStatus.className = 'text-sm text-blue-600';
                        fetch(restBase + '/agent/latest?plugin=analytics', {
                            credentials: 'same-origin',
                            headers: { 'X-WP-Nonce': nonce }
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(data) {
                            if (data.agent_md) {
                                downloadBlob(data.agent_md, data.filename);
                                agentStatus.textContent = 'Downloaded latest agent (v' + (data.version || '?') + '). Replace your existing file in .claude/agents/ or .gemini/agents/ — your key is unchanged.';
                                agentStatus.className = 'text-sm text-green-600';
                            } else {
                                agentStatus.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (data.message || '<?php echo esc_js( __( 'Unknown error', 'kantan-analytics' ) ); ?>');
                                agentStatus.className = 'text-sm text-red-600';
                            }
                            updateBtn.disabled = false;
                        })
                        .catch(function(err) {
                            agentStatus.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message;
                            agentStatus.className = 'text-sm text-red-600';
                            updateBtn.disabled = false;
                        });
                    });
                }

                if (agentCopy) {
                    agentCopy.addEventListener('click', function() {
                        navigator.clipboard.writeText(agentEnv.textContent).then(function() {
                            agentCopy.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>';
                            setTimeout(function() {
                                agentCopy.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>';
                            }, 2000);
                        });
                    });
                }
            })();
            <?php kantan_admin_inline_js( ob_get_clean() ); ?>

        </div>

        <?php ob_start(); ?>
        (function() {
            var links = <?php echo json_encode(get_option('kantan_conversion_links', array())); ?>;
            var list = document.getElementById('kantan-cl-list');
            var addBtn = document.getElementById('kantan-cl-add');
            var saveBtn = document.getElementById('kantan-cl-save');
            var status = document.getElementById('kantan-cl-status');

            function renderRow(link, index) {
                var div = document.createElement('div');
                div.className = 'flex flex-wrap items-start gap-3 p-4 bg-gray-50 rounded-lg border';
                div.setAttribute('data-index', index);
                div.innerHTML = ''
                    + '<div class="flex-1 min-w-[200px]">'
                    + '  <label class="block text-xs font-medium text-gray-500 mb-1"><?php echo esc_js( __( 'Domain', 'kantan-analytics' ) ); ?></label>'
                    + '  <input type="text" data-field="domain" value="' + esc(link.domain || '') + '"'
                    + '    placeholder="<?php echo esc_js( __( 'e.g. clients.uschedule.com', 'kantan-analytics' ) ); ?>"'
                    + '    class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">'
                    + '</div>'
                    + '<div class="w-36">'
                    + '  <label class="block text-xs font-medium text-gray-500 mb-1"><?php echo esc_js( __( 'Label', 'kantan-analytics' ) ); ?></label>'
                    + '  <input type="text" data-field="label" value="' + esc(link.label || '') + '"'
                    + '    placeholder="<?php echo esc_js( __( 'e.g. Booking', 'kantan-analytics' ) ); ?>"'
                    + '    class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">'
                    + '</div>'
                    + '<div class="w-40">'
                    + '  <label class="block text-xs font-medium text-gray-500 mb-1"><?php echo esc_js( __( 'Conversion Type', 'kantan-analytics' ) ); ?></label>'
                    + '  <input type="text" data-field="type" value="' + esc(link.type || 'outbound_click') + '"'
                    + '    placeholder="<?php echo esc_js( __( 'e.g. booking_click', 'kantan-analytics' ) ); ?>"'
                    + '    class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">'
                    + '</div>'
                    + '<div class="w-20 pt-6">'
                    + '  <label class="flex items-center gap-2 cursor-pointer">'
                    + '    <input type="checkbox" data-field="utm"' + (link.utm ? ' checked' : '')
                    + '      class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">'
                    + '    <span class="text-sm text-gray-600">UTM</span>'
                    + '  </label>'
                    + '</div>'
                    + '<div class="pt-6">'
                    + '  <button type="button" class="kantan-cl-remove p-2 text-gray-400 hover:text-red-500 transition">'
                    + '    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>'
                    + '  </button>'
                    + '</div>';
                return div;
            }

            function esc(str) {
                var d = document.createElement('div');
                d.textContent = str;
                return d.innerHTML.replace(/"/g, '&quot;');
            }

            function renderAll() {
                list.innerHTML = '';
                if (links.length === 0) {
                    list.innerHTML = '<p class="text-gray-400 text-sm py-2"><?php echo esc_js( __( 'No conversion links configured. Click "Add Conversion Link" to get started.', 'kantan-analytics' ) ); ?></p>';
                    return;
                }
                links.forEach(function(link, i) {
                    list.appendChild(renderRow(link, i));
                });
            }

            function collectData() {
                var rows = list.querySelectorAll('[data-index]');
                var result = [];
                rows.forEach(function(row) {
                    var domain = row.querySelector('[data-field="domain"]').value.trim();
                    if (!domain) return;
                    result.push({
                        domain: domain,
                        label: row.querySelector('[data-field="label"]').value.trim(),
                        type: row.querySelector('[data-field="type"]').value.trim() || 'outbound_click',
                        utm: row.querySelector('[data-field="utm"]').checked,
                    });
                });
                return result;
            }

            addBtn.addEventListener('click', function() {
                links.push({ domain: '', label: '', type: 'outbound_click', utm: true });
                renderAll();
                // Focus the new domain input
                var inputs = list.querySelectorAll('[data-field="domain"]');
                if (inputs.length) inputs[inputs.length - 1].focus();
            });

            list.addEventListener('click', function(e) {
                var btn = e.target.closest('.kantan-cl-remove');
                if (!btn) return;
                var row = btn.closest('[data-index]');
                var idx = parseInt(row.getAttribute('data-index'));
                links.splice(idx, 1);
                renderAll();
            });

            saveBtn.addEventListener('click', function() {
                var data = collectData();
                status.textContent = '<?php echo esc_js( __( 'Saving...', 'kantan-analytics' ) ); ?>';
                saveBtn.disabled = true;

                fetch('<?php echo esc_url(rest_url('kantan/v1/conversion-links')); ?>', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                    },
                    body: JSON.stringify({ links: data })
                })
                .then(function(r) { return r.json(); })
                .then(function(resp) {
                    if (resp.updated) {
                        links = resp.links;
                        status.textContent = '<?php echo esc_js( __( 'Saved!', 'kantan-analytics' ) ); ?>';
                        status.className = 'text-sm text-green-600';
                        renderAll();
                    } else {
                        status.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + (resp.message || '<?php echo esc_js( __( 'Unknown', 'kantan-analytics' ) ); ?>');
                        status.className = 'text-sm text-red-600';
                    }
                    saveBtn.disabled = false;
                    setTimeout(function() { status.textContent = ''; status.className = 'text-sm text-gray-500'; }, 3000);
                })
                .catch(function(err) {
                    status.textContent = '<?php echo esc_js( __( 'Error: ', 'kantan-analytics' ) ); ?>' + err.message;
                    status.className = 'text-sm text-red-600';
                    saveBtn.disabled = false;
                });
            });

            renderAll();
        })();
        <?php kantan_admin_inline_js( ob_get_clean() ); ?>

        <?php else: ?>
            <?php
            // Allow companion plugins to render their tab content
            do_action('kantan_analytics_render_tab', $current_tab, $days);
            ?>

        <?php endif; ?>

            </div><!-- .flex-1 main content -->

        </div><!-- .flex sidebar+content -->

    </div>
</div>

<!-- Realtime poller: drives both the nav badge (every tab) and the Realtime tab table.
     One fetch every 30s — when on the Realtime tab the same response also refreshes
     the table and resets the countdown ticker. Pauses when the document is hidden. -->
<?php ob_start(); ?>
(function() {
    'use strict';

    var REST_URL = '<?php echo esc_url(rest_url('kantan/v1/realtime')); ?>';
    var NONCE    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var INTERVAL = 30;

    var ticksRemaining = INTERVAL;
    var countdownTimer = null;
    var inFlight = false;

    function el(id) { return document.getElementById(id); }

    function formatDuration(s) {
        s = Math.max(0, parseInt(s, 10) || 0);
        if (s < 60) return s + 's';
        var m = Math.floor(s / 60);
        var r = s % 60;
        return m + 'm ' + (r ? r + 's' : '');
    }

    function formatLastSeen(s) {
        s = parseInt(s, 10) || 0;
        if (s < 10) return '<?php echo esc_js( __( 'just now', 'kantan-analytics' ) ); ?>';
        if (s < 60) return '<?php echo esc_js( __( '%s sec ago', 'kantan-analytics' ) ); ?>'.replace('%s', s);
        return '<?php echo esc_js( __( '%s min ago', 'kantan-analytics' ) ); ?>'.replace('%s', Math.floor(s / 60));
    }

    function pageLabel(url, title) {
        if (title) return title;
        try { return new URL(url).pathname || '/'; } catch (e) { return url || '<?php echo esc_js( __( '(unknown)', 'kantan-analytics' ) ); ?>'; }
    }

    var SOURCE_CLS = {
        organic:  'bg-green-100 text-green-700',
        direct:   'bg-gray-100 text-gray-700',
        social:   'bg-purple-100 text-purple-700',
        referral: 'bg-blue-100 text-blue-700',
        ai:       'bg-amber-100 text-amber-700'
    };

    var SOURCE_LABEL = { ai: '<?php echo esc_js( __( 'AI assistants', 'kantan-analytics' ) ); ?>' };

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }

    function updateBadge(count) {
        var badge = el('kantan-realtime-badge');
        if (!badge) return;
        if (count > 0) {
            badge.classList.remove('hidden');
            var cnt = badge.querySelector('[data-count]');
            if (cnt) cnt.textContent = count;
        } else {
            badge.classList.add('hidden');
        }
    }

    function updateTab(data) {
        var countEl  = el('kantan-realtime-count');
        var tbodyEl  = el('kantan-realtime-tbody');
        var emptyEl  = el('kantan-realtime-empty');
        if (!countEl) return; // not on the realtime tab

        var count    = data.count || 0;
        var visitors = data.visitors || [];

        countEl.textContent = count;

        if (!visitors.length) {
            tbodyEl.innerHTML = '';
            if (emptyEl) emptyEl.classList.remove('hidden');
            return;
        }
        if (emptyEl) emptyEl.classList.add('hidden');

        tbodyEl.innerHTML = visitors.map(function(v) {
            var src = (v.traffic_source || 'unknown').toLowerCase();
            var srcCls = SOURCE_CLS[src] || 'bg-gray-100 text-gray-700';
            var page = pageLabel(v.current_page, v.current_page_title);
            var nameCell = v.visitor_id
                ? '<button type="button" class="kantan-visitor-history text-blue-600 hover:underline font-medium text-left" data-visitor-id="' + esc(v.visitor_id) + '">' + esc(v.display_name || '<?php echo esc_js( __( 'Anonymous', 'kantan-analytics' ) ); ?>') + '</button>'
                : '<span class="text-gray-900">' + esc(v.display_name || '<?php echo esc_js( __( 'Anonymous', 'kantan-analytics' ) ); ?>') + '</span>';
            return '<tr>'
                + '<td class="px-6 py-3 text-sm font-medium">' + nameCell + '</td>'
                + '<td class="px-6 py-3 text-sm text-gray-700 truncate" style="max-width:340px" title="' + esc(v.current_page) + '">' + esc(page) + '</td>'
                + '<td class="px-6 py-3 text-sm"><span class="' + srcCls + ' px-2 py-0.5 rounded text-xs font-medium capitalize">' + esc(SOURCE_LABEL[src] || src) + '</span></td>'
                + '<td class="px-6 py-3 text-sm text-gray-700">' + (parseInt(v.page_count, 10) || 1) + '</td>'
                + '<td class="px-6 py-3 text-sm text-gray-700">' + formatDuration(v.session_age_seconds) + '</td>'
                + '<td class="px-6 py-3 text-sm text-gray-500">' + formatLastSeen(v.seconds_since_seen) + '</td>'
                + '</tr>';
        }).join('');
    }

    function tickCountdown() {
        var c = el('kantan-realtime-countdown');
        if (c) c.textContent = ticksRemaining + 's';
    }

    function fetchOnce() {
        if (inFlight) return;
        inFlight = true;
        fetch(REST_URL, {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': NONCE }
        })
        .then(function(r) { return r.ok ? r.json() : Promise.reject(r); })
        .then(function(data) {
            updateBadge(data.count || 0);
            updateTab(data);
            ticksRemaining = INTERVAL;
            tickCountdown();
        })
        .catch(function() { /* silent — keep polling on next tick */ })
        .then(function() { inFlight = false; });
    }

    function startTimers() {
        stopTimers();
        countdownTimer = setInterval(function() {
            ticksRemaining = Math.max(0, ticksRemaining - 1);
            tickCountdown();
            if (ticksRemaining === 0) fetchOnce();
        }, 1000);
    }

    function stopTimers() {
        if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }
    }

    document.addEventListener('DOMContentLoaded', function() {
        fetchOnce();
        startTimers();

        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                stopTimers();
            } else {
                fetchOnce();
                startTimers();
            }
        });

        var refresh = el('kantan-realtime-refresh');
        if (refresh) {
            refresh.addEventListener('click', function() {
                ticksRemaining = INTERVAL;
                fetchOnce();
            });
        }
    });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- Chart.js Script (only needed for overview tab) -->
<?php if ($current_tab === 'overview'): ?>
<?php ob_start(); ?>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('visitsChart');
    if (ctx) {
        const visitsData = <?php echo json_encode(array_map(function($v) { return $v->visits; }, $visits_by_day)); ?>;
        const visitsDates = <?php echo json_encode(array_map(function($v) { return gmdate('M j', strtotime($v->date)); }, $visits_by_day)); ?>;

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: visitsDates,
                datasets: [{
                    label: '<?php echo esc_js( __( 'Visits', 'kantan-analytics' ) ); ?>',
                    data: visitsData,
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
            }
        });
    }
});
<?php kantan_admin_inline_js( ob_get_clean() ); ?>
<?php endif; // end overview-only chart ?>

<!-- Page detail click handler + upsell fallback (global — page-link rows appear on every tab) -->
<div id="kantan-upsell-modal" class="fixed inset-0 z-[99999] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/50" id="kantan-upsell-backdrop"></div>
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-md p-8 text-center" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-sky-400 to-indigo-500 rounded-2xl flex items-center justify-center">
            <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path></svg>
        </div>
        <h2 class="text-xl font-bold text-gray-900 mb-2"><?php esc_html_e('Unlock Page Analytics', 'kantan-analytics'); ?></h2>
        <p class="text-gray-600 text-sm mb-6"><?php echo wp_kses_post( __( 'Get detailed page-level insights including keyword rankings, organic traffic trends, PageSpeed scores, health audits, and conversion tracking with <strong>Kantan SEO</strong>.', 'kantan-analytics' ) ); ?></p>
        <div class="space-y-3">
            <a href="<?php echo esc_url('https://trykantan.com/seo/'); ?>" target="_blank" class="block w-full px-4 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition text-sm"><?php esc_html_e('Learn More About Kantan SEO', 'kantan-analytics'); ?></a>
            <button type="button" id="kantan-upsell-close" class="block w-full px-4 py-2 text-gray-500 hover:text-gray-700 text-sm transition"><?php esc_html_e('Maybe Later', 'kantan-analytics'); ?></button>
        </div>
    </div>
</div>
<?php ob_start(); ?>
(function() {
    'use strict';
    var upsell = document.getElementById('kantan-upsell-modal');
    var upsellClose = document.getElementById('kantan-upsell-close');
    var upsellBackdrop = document.getElementById('kantan-upsell-backdrop');

    function closeUpsell() { if (upsell) upsell.classList.add('hidden'); }
    if (upsellClose) upsellClose.addEventListener('click', closeUpsell);
    if (upsellBackdrop) upsellBackdrop.addEventListener('click', closeUpsell);
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeUpsell(); });

    document.addEventListener('click', function(e) {
        var link = e.target.closest('.kantan-page-link');
        if (!link) return;
        e.preventDefault();
        e.stopPropagation();
        var url = link.getAttribute('data-page-url');
        var title = link.getAttribute('data-page-title');
        if (typeof window.kantanOpenPageDetail === 'function') {
            window.kantanOpenPageDetail(url, title);
        } else if (upsell) {
            upsell.classList.remove('hidden');
        }
    });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<?php ob_start(); ?>
(function() {
    'use strict';
    document.querySelectorAll('.kantan-nav-group-toggle').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var group   = btn.closest('.kantan-nav-group');
            var items   = group.querySelector('.kantan-nav-group-items');
            var chevron = btn.querySelector('.kantan-nav-chevron');
            var isOpen  = btn.getAttribute('aria-expanded') === 'true';
            if (isOpen) {
                items.classList.add('hidden');
                chevron.classList.remove('rotate-180');
                btn.setAttribute('aria-expanded', 'false');
            } else {
                items.classList.remove('hidden');
                chevron.classList.add('rotate-180');
                btn.setAttribute('aria-expanded', 'true');
            }
        });
    });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== TOP REFERRERS DETAIL MODAL ==================== -->
<div id="kantan-referrer-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-ref-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-3xl" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl z-10">
            <div class="min-w-0 pr-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-purple-600 mb-1"><?php esc_html_e('Referrer', 'kantan-analytics'); ?></p>
                <h3 id="kantan-ref-title" class="text-xl font-bold text-gray-900 truncate">&nbsp;</h3>
                <p id="kantan-ref-sub" class="text-sm text-gray-500 mt-0.5"></p>
            </div>
            <button type="button" data-ref-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div id="kantan-ref-body" class="p-6"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanReferrerInit) return;
    window.__kantanReferrerInit = true;

    var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var days     = <?php echo (int) $days; ?>;

    var modal = document.getElementById('kantan-referrer-modal');
    var title = document.getElementById('kantan-ref-title');
    var sub   = document.getElementById('kantan-ref-sub');
    var body  = document.getElementById('kantan-ref-body');

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }
    function fmtDur(s) {
        s = parseInt(s, 10) || 0;
        if (s < 60) return s + 's';
        var m = Math.floor(s / 60), r = s % 60;
        return m + 'm' + (r ? ' ' + r + 's' : '');
    }
    function fmtDate(str) {
        if (!str) return '';
        var p = String(str).split(/[ T]/), d = (p[0] || '').split('-'), t = (p[1] || '').split(':');
        var mon = <?php echo $kantan_js_months_json; ?>[parseInt(d[1], 10) - 1] || '';
        var hh = parseInt(t[0] || 0, 10), ap = hh >= 12 ? <?php echo wp_json_encode($kantan_js_ampm['pm']); ?> : <?php echo wp_json_encode($kantan_js_ampm['am']); ?>, h12 = hh % 12 || 12;
        return mon + ' ' + parseInt(d[2], 10) + ', ' + h12 + ':' + (t[1] || '00') + ' ' + ap;
    }
    function pathOf(url) {
        try { var u = new URL(url); return (u.pathname || '/') + (u.search || ''); }
        catch (e) { return url || '/'; }
    }
    function trimProto(url) { return String(url || '').replace(/^https?:\/\//, ''); }

    function open() { modal.classList.remove('hidden'); }
    function close() { modal.classList.add('hidden'); }

    function kpi(label, val) {
        return '<div class="bg-gray-50 rounded-lg p-3">' +
            '<p class="text-xs text-gray-500 uppercase tracking-wide">' + esc(label) + '</p>' +
            '<p class="text-xl font-bold text-gray-900 mt-1">' + val + '</p></div>';
    }

    function listBlock(heading, rows) {
        return '<div><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">' + esc(heading) + '</h4>' +
            '<div class="space-y-1">' + rows + '</div></div>';
    }

    function render(data) {
        var s = data.summary || {};
        title.textContent = data.domain || '<?php echo esc_js( __( 'Referrer', 'kantan-analytics' ) ); ?>';
        var _sc = (s.sessions || 0);
        sub.textContent = (_sc === 1
            ? '<?php echo esc_js( __( '%1$s session over the last %2$s days', 'kantan-analytics' ) ); ?>'
            : '<?php echo esc_js( __( '%1$s sessions over the last %2$s days', 'kantan-analytics' ) ); ?>'
            ).replace('%1$s', _sc).replace('%2$s', days) +
            (s.last_seen ? ' · ' + '<?php echo esc_js( __( 'last seen', 'kantan-analytics' ) ); ?>' + ' ' + fmtDate(s.last_seen) : '');

        var html = '';

        // KPI grid
        html += '<div class="grid grid-cols-2 md:grid-cols-3 gap-3 mb-6">' +
            kpi('<?php echo esc_js( __( 'Sessions', 'kantan-analytics' ) ); ?>', (s.sessions || 0)) +
            kpi('<?php echo esc_js( __( 'Visitors', 'kantan-analytics' ) ); ?>', (s.visitors || 0)) +
            kpi('<?php echo esc_js( __( 'Pageviews', 'kantan-analytics' ) ); ?>', (s.pageviews || 0)) +
            kpi('<?php echo esc_js( __( 'Avg. Duration', 'kantan-analytics' ) ); ?>', fmtDur(s.avg_duration)) +
            kpi('<?php echo esc_js( __( 'Bounce Rate', 'kantan-analytics' ) ); ?>', (s.bounce_rate || 0) + '%') +
            kpi('<?php echo esc_js( __( 'Conversions', 'kantan-analytics' ) ); ?>', (s.conversions || 0)) +
            '</div>';

        // Daily trend sparkline
        var byDay = data.by_day || [];
        if (byDay.length > 1) {
            var max = Math.max.apply(null, byDay.map(function(d) { return +d.visits; }).concat([1]));
            var bars = byDay.map(function(d) {
                var h = Math.max(6, Math.round((+d.visits / max) * 100));
                return '<div class="flex-1 bg-purple-200 rounded-t" style="height:' + h + '%" title="' + esc(d.day) + ': ' + d.visits + '"></div>';
            }).join('');
            html += '<div class="mb-6"><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2"><?php echo esc_js( __( 'Daily Sessions', 'kantan-analytics' ) ); ?></h4>' +
                '<div class="flex items-end gap-0.5 bg-gray-50 rounded-lg p-2" style="height:56px;">' + bars + '</div></div>';
        }

        // Landing pages + referring URLs
        var cols = [];
        var landing = (data.pages_visited || []).map(function(p) {
            return '<div class="flex items-center justify-between gap-2 text-sm py-1 border-b border-gray-50 last:border-0 cursor-pointer hover:bg-gray-50 rounded px-1 -mx-1 kantan-page-link" data-page-url="' + esc(p.page_url) + '" data-page-title="' + esc(p.page_title || p.page_url) + '">' +
                '<span class="text-gray-700 truncate" title="' + esc(p.page_url) + '">' + esc(pathOf(p.page_url)) + '</span>' +
                '<span class="text-gray-400 text-xs flex-shrink-0">' + p.visits + '</span></div>';
        }).join('') || '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No data', 'kantan-analytics' ) ); ?></p>';
        cols.push(listBlock('<?php echo esc_js( __( 'Landing Pages', 'kantan-analytics' ) ); ?>', landing));

        if (!data.is_direct) {
            var refs = (data.referrer_urls || []).map(function(r) {
                return '<div class="flex items-center justify-between gap-2 text-sm py-1 border-b border-gray-50 last:border-0">' +
                    '<a href="' + esc(r.referrer) + '" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline truncate" title="' + esc(r.referrer) + '">' + esc(trimProto(r.referrer)) + '</a>' +
                    '<span class="text-gray-400 text-xs flex-shrink-0">' + r.visits + '</span></div>';
            }).join('') || '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No data', 'kantan-analytics' ) ); ?></p>';
            cols.push(listBlock('<?php echo esc_js( __( 'Referring URLs', 'kantan-analytics' ) ); ?>', refs));
        }

        html += '<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">' + cols.join('') + '</div>';

        // Recent visitors
        var vis = (data.visitors || []).map(function(v) {
            var badges = '';
            if (parseInt(v.is_bounce, 10) === 1) badges += '<span class="px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded text-xs"><?php echo esc_js( __( 'bounce', 'kantan-analytics' ) ); ?></span>';
            if (parseInt(v.conversions, 10) > 0) badges += '<span class="px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-xs">' + v.conversions + ' conv</span>';
            return '<div class="flex items-center justify-between gap-3 py-2 border-b border-gray-50 last:border-0">' +
                '<div class="min-w-0 flex-1">' +
                    '<p class="text-sm font-medium text-gray-900 truncate">' + esc(v.display_name || '<?php echo esc_js( __( 'Anonymous', 'kantan-analytics' ) ); ?>') + '</p>' +
                    '<p class="text-xs text-gray-400 truncate kantan-page-link cursor-pointer hover:text-gray-600" data-page-url="' + esc(v.page_url) + '" data-page-title="' + esc(v.page_title || v.page_url) + '" title="' + esc(v.page_url) + '">' + esc(pathOf(v.page_url)) + '</p>' +
                '</div>' +
                '<div class="flex items-center gap-2 flex-shrink-0">' + badges +
                    '<span class="text-xs text-gray-500">' + fmtDur(v.visit_duration) + '</span>' +
                    '<span class="text-xs text-gray-400 w-28 text-right">' + fmtDate(v.visit_date) + '</span>' +
                '</div></div>';
        }).join('') || '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No visitors in this period', 'kantan-analytics' ) ); ?></p>';
        html += '<div><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2"><?php echo esc_js( __( 'Recent Visitors', 'kantan-analytics' ) ); ?></h4>' + vis + '</div>';

        body.innerHTML = html;
    }

    // Open on referrer-row click (delegated)
    document.addEventListener('click', function(e) {
        var row = e.target.closest('.kantan-referrer-link');
        if (!row) return;
        var domain = row.getAttribute('data-referrer-domain') || '';
        title.textContent = domain;
        sub.textContent = '<?php echo esc_js( __( 'Loading…', 'kantan-analytics' ) ); ?>';
        body.innerHTML = '<div class="py-12 text-center text-gray-400"><?php echo esc_js( __( 'Loading referrer detail…', 'kantan-analytics' ) ); ?></div>';
        open();
        fetch(restBase + '/referrers/detail?days=' + days + '&domain=' + encodeURIComponent(domain), {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(function(r) { return r.json(); })
        .then(render)
        .catch(function() {
            body.innerHTML = '<div class="py-12 text-center text-red-500"><?php echo esc_js( __( 'Could not load referrer detail. Please try again.', 'kantan-analytics' ) ); ?></div>';
        });
    });

    // Close handlers
    document.addEventListener('click', function(e) { if (e.target.closest('[data-ref-close]')) close(); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) close(); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== ALL REFERRERS MODAL ====================
     The block above lists only the top 10. This shows every referrer in the
     period. Rows reuse .kantan-referrer-link, so the per-domain detail modal
     opens on top of this one (hence the lower z-index).
-->
<div id="kantan-referrers-all-modal" class="fixed inset-0 z-[2147483546] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-refs-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-2xl flex flex-col" style="transform:translate(-50%,-50%);max-height:85vh;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 flex-shrink-0">
            <div class="min-w-0 pr-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-purple-600 mb-1"><?php esc_html_e('Referrers', 'kantan-analytics'); ?></p>
                <h3 class="text-xl font-bold text-gray-900"><?php esc_html_e('All Referrers', 'kantan-analytics'); ?></h3>
                <p id="kantan-refs-sub" class="text-sm text-gray-500 mt-0.5"></p>
            </div>
            <button type="button" data-refs-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div class="px-6 pt-4 flex-shrink-0">
            <input type="search" id="kantan-refs-filter" autocomplete="off"
                   class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                   placeholder="<?php esc_attr_e('Filter referrers…', 'kantan-analytics'); ?>">
        </div>
        <div id="kantan-refs-body" class="p-6 pt-4 overflow-y-auto"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanReferrersAllInit) return;
    window.__kantanReferrersAllInit = true;

    var openBtn = document.getElementById('kantan-referrers-all-open');
    if (!openBtn) return; // nothing held back — the button isn't rendered

    var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var days     = <?php echo (int) $days; ?>;

    var modal  = document.getElementById('kantan-referrers-all-modal');
    var detail = document.getElementById('kantan-referrer-modal');
    var sub    = document.getElementById('kantan-refs-sub');
    var body   = document.getElementById('kantan-refs-body');
    var filter = document.getElementById('kantan-refs-filter');

    var rows = null; // cached payload

    function open() { modal.classList.remove('hidden'); }
    function close() { modal.classList.add('hidden'); }
    function isOpen() { return !modal.classList.contains('hidden'); }
    function detailOpen() { return detail && !detail.classList.contains('hidden'); }

    function note(msg, cls) {
        body.textContent = '';
        var p = document.createElement('p');
        p.className = 'py-10 text-center text-sm ' + (cls || 'text-gray-400');
        p.textContent = msg;
        body.appendChild(p);
    }

    /**
     * Build each row with DOM APIs rather than an HTML string: the domain comes
     * from the visitor's Referer header and lands in a data- attribute, so
     * string concatenation here would be an attribute-injection hole.
     */
    function render(list) {
        body.textContent = '';

        if (!list.length) {
            note('<?php echo esc_js( __( 'No referrers match that filter.', 'kantan-analytics' ) ); ?>');
            return;
        }

        var wrap = document.createElement('div');
        wrap.className = 'space-y-1';

        list.forEach(function(r) {
            var row = document.createElement('div');
            row.className = 'flex items-center py-3 border-b border-gray-100 last:border-0 cursor-pointer hover:bg-gray-50 rounded-lg px-2 -mx-2 transition kantan-referrer-link';
            row.setAttribute('data-referrer-domain', r.domain);

            var name = document.createElement('div');
            name.className = 'min-w-0 flex-1 mr-4';
            var p = document.createElement('p');
            p.className = 'text-sm font-medium text-gray-900 truncate';
            p.textContent = r.domain;
            name.appendChild(p);

            var chev = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            chev.setAttribute('class', 'w-4 h-4 text-gray-300 mr-2 flex-shrink-0');
            chev.setAttribute('fill', 'none');
            chev.setAttribute('stroke', 'currentColor');
            chev.setAttribute('viewBox', '0 0 24 24');
            var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            path.setAttribute('stroke-linecap', 'round');
            path.setAttribute('stroke-linejoin', 'round');
            path.setAttribute('stroke-width', '2');
            path.setAttribute('d', 'M9 5l7 7-7 7');
            chev.appendChild(path);

            var count = document.createElement('span');
            count.className = 'flex-shrink-0 px-3 py-1 bg-blue-100 text-blue-800 text-sm font-medium rounded-full';
            count.textContent = Number(r.visits || 0).toLocaleString();

            row.appendChild(name);
            row.appendChild(chev);
            row.appendChild(count);
            wrap.appendChild(row);
        });

        body.appendChild(wrap);
    }

    function applyFilter() {
        if (!rows) return;
        var q = (filter.value || '').trim().toLowerCase();
        render(!q ? rows : rows.filter(function(r) {
            return String(r.domain || '').toLowerCase().indexOf(q) !== -1;
        }));
    }

    openBtn.addEventListener('click', function() {
        open();
        if (rows) { applyFilter(); return; } // already fetched this page load

        filter.value = '';
        note('<?php echo esc_js( __( 'Loading referrers…', 'kantan-analytics' ) ); ?>');

        fetch(restBase + '/referrers?days=' + days + '&limit=500', {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            rows = (data && data.referrers) || [];
            var total = (data && data.total) || rows.length;
            var shown = rows.length;
            sub.textContent = shown < total
                ? <?php echo wp_json_encode( __( 'Showing %1$s of %2$s referrers', 'kantan-analytics' ) ); ?>
                    .replace('%1$s', shown.toLocaleString()).replace('%2$s', total.toLocaleString())
                : <?php echo wp_json_encode( __( '%s referrers', 'kantan-analytics' ) ); ?>
                    .replace('%s', total.toLocaleString());
            applyFilter();
        })
        .catch(function() {
            note('<?php echo esc_js( __( 'Could not load referrers. Please try again.', 'kantan-analytics' ) ); ?>', 'text-red-500');
        });
    });

    filter.addEventListener('input', applyFilter);

    document.addEventListener('click', function(e) { if (e.target.closest('[data-refs-close]')) close(); });

    // Escape closes the detail modal first (it sits on top of this one); a second
    // press closes this list. Runs in the CAPTURE phase so it evaluates BEFORE
    // the detail modal's own (bubble-phase) Escape handler: otherwise that one
    // closes the detail first and this handler then sees detailOpen() === false
    // in the same event and wrongly closes the list too, collapsing both at once.
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && isOpen() && !detailOpen()) close();
    }, true);
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== CLICK REGION DETAIL MODAL ==================== -->
<div id="kantan-region-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-region-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-3xl" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl z-10">
            <div class="min-w-0 pr-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-purple-600 mb-1"><?php esc_html_e('Click Region', 'kantan-analytics'); ?></p>
                <h3 id="kantan-region-title" class="text-xl font-bold text-gray-900 truncate">&nbsp;</h3>
                <p id="kantan-region-sub" class="text-sm text-gray-500 mt-0.5"></p>
            </div>
            <button type="button" data-region-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div id="kantan-region-body" class="p-6"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanRegionInit) return;
    window.__kantanRegionInit = true;

    var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var days     = <?php echo (int) $days; ?>;

    var modal = document.getElementById('kantan-region-modal');
    var title = document.getElementById('kantan-region-title');
    var sub   = document.getElementById('kantan-region-sub');
    var body  = document.getElementById('kantan-region-body');

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }
    function pathOf(url) {
        try { var u = new URL(url); return (u.pathname || '/') + (u.search || ''); }
        catch (e) { return url || '/'; }
    }

    function open() { modal.classList.remove('hidden'); }
    function close() { modal.classList.add('hidden'); }

    function render(label, data) {
        var total = data.total_clicks || 0;
        title.textContent = '<?php echo esc_js( __( 'Click Region: ', 'kantan-analytics' ) ); ?>' + label;
        sub.textContent = (total === 1
            ? '<?php echo esc_js( __( '%1$s click in this region · last %2$s days', 'kantan-analytics' ) ); ?>'
            : '<?php echo esc_js( __( '%1$s clicks in this region · last %2$s days', 'kantan-analytics' ) ); ?>'
            ).replace('%1$s', total.toLocaleString()).replace('%2$s', days);

        var html = '';

        // What was clicked
        var els = data.elements || [];
        var rows = els.map(function(el) {
            var text = (el.element_text && el.element_text.trim() !== '') ? el.element_text : '<?php echo esc_js( __( '(no text)', 'kantan-analytics' ) ); ?>';
            var muted = (el.element_text && el.element_text.trim() !== '') ? '' : ' italic text-gray-400';
            return '<tr class="hover:bg-gray-50">' +
                '<td class="py-2 pr-3"><div class="text-sm text-gray-900 truncate' + muted + '" style="max-width:280px" title="' + esc(el.element_text || '') + '">' + esc(text) + '</div></td>' +
                '<td class="py-2 pr-3 whitespace-nowrap"><span class="px-2 py-0.5 text-xs font-mono bg-gray-100 text-gray-700 rounded">&lt;' + esc(el.element_tag || '?') + '&gt;</span></td>' +
                '<td class="py-2 pr-3"><span class="text-xs text-gray-500 truncate kantan-page-link cursor-pointer hover:text-gray-800 block" style="max-width:200px" data-page-url="' + esc(el.page_url) + '" data-page-title="' + esc(el.page_url) + '" title="' + esc(el.page_url) + '">' + esc(pathOf(el.page_url)) + '</span></td>' +
                '<td class="py-2 text-right whitespace-nowrap"><span class="px-2.5 py-0.5 text-xs font-semibold rounded-full bg-orange-100 text-orange-800">' + el.clicks + '</span></td>' +
                '</tr>';
        }).join('');

        html += '<h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2"><?php echo esc_js( __( 'What was clicked here', 'kantan-analytics' ) ); ?></h4>';
        if (rows) {
            html += '<div class="overflow-x-auto mb-6"><table class="min-w-full"><thead><tr class="text-left text-xs text-gray-400 border-b border-gray-100">' +
                '<th class="py-1 pr-3 font-medium"><?php echo esc_js( __( 'Element', 'kantan-analytics' ) ); ?></th><th class="py-1 pr-3 font-medium"><?php echo esc_js( __( 'Type', 'kantan-analytics' ) ); ?></th><th class="py-1 pr-3 font-medium"><?php echo esc_js( __( 'Page', 'kantan-analytics' ) ); ?></th><th class="py-1 text-right font-medium"><?php echo esc_js( __( 'Clicks', 'kantan-analytics' ) ); ?></th>' +
                '</tr></thead><tbody class="divide-y divide-gray-50">' + rows + '</tbody></table></div>';
        } else {
            html += '<p class="text-gray-400 italic text-sm mb-6"><?php echo esc_js( __( 'No element data captured for this region.', 'kantan-analytics' ) ); ?></p>';
        }

        // Pages rollup
        var pages = data.pages || [];
        var pageRows = pages.map(function(p) {
            return '<div class="flex items-center justify-between gap-2 text-sm py-1 border-b border-gray-50 last:border-0 cursor-pointer hover:bg-gray-50 rounded px-1 -mx-1 kantan-page-link" data-page-url="' + esc(p.page_url) + '" data-page-title="' + esc(p.page_url) + '">' +
                '<span class="text-gray-700 truncate" title="' + esc(p.page_url) + '">' + esc(pathOf(p.page_url)) + '</span>' +
                '<span class="text-gray-400 text-xs flex-shrink-0">' + p.clicks + '</span></div>';
        }).join('');
        html += '<h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2"><?php echo esc_js( __( 'Pages with clicks in this region', 'kantan-analytics' ) ); ?></h4>';
        html += pageRows ? '<div class="space-y-1">' + pageRows + '</div>' : '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No page data.', 'kantan-analytics' ) ); ?></p>';

        body.innerHTML = html;
    }

    // Open on region-cell click (delegated)
    document.addEventListener('click', function(e) {
        var cell = e.target.closest('.kantan-region-link');
        if (!cell) return;
        var region = cell.getAttribute('data-region');
        var label  = cell.getAttribute('data-region-label') || ('Region ' + region);
        title.textContent = '<?php echo esc_js( __( 'Click Region: ', 'kantan-analytics' ) ); ?>' + label;
        sub.textContent = '<?php echo esc_js( __( 'Loading…', 'kantan-analytics' ) ); ?>';
        body.innerHTML = '<div class="py-12 text-center text-gray-400"><?php echo esc_js( __( 'Loading region detail…', 'kantan-analytics' ) ); ?></div>';
        open();
        fetch(restBase + '/interactions/region?region=' + encodeURIComponent(region) + '&days=' + days, {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) { render(label, data); })
        .catch(function() {
            body.innerHTML = '<div class="py-12 text-center text-red-500"><?php echo esc_js( __( 'Could not load region detail. Please try again.', 'kantan-analytics' ) ); ?></div>';
        });
    });

    document.addEventListener('click', function(e) { if (e.target.closest('[data-region-close]')) close(); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) close(); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== CLICKED ELEMENT DETAIL MODAL ==================== -->
<div id="kantan-element-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-element-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-2xl" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl z-10">
            <div class="min-w-0 pr-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-purple-600 mb-1"><?php esc_html_e('Clicked Element', 'kantan-analytics'); ?></p>
                <h3 id="kantan-element-title" class="text-xl font-bold text-gray-900 truncate">&nbsp;</h3>
                <p id="kantan-element-sub" class="text-sm text-gray-500 mt-0.5"></p>
            </div>
            <button type="button" data-element-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div id="kantan-element-body" class="p-6"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanElementInit) return;
    window.__kantanElementInit = true;

    var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var days     = <?php echo (int) $days; ?>;

    var modal = document.getElementById('kantan-element-modal');
    var title = document.getElementById('kantan-element-title');
    var sub   = document.getElementById('kantan-element-sub');
    var body  = document.getElementById('kantan-element-body');

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }
    function pathOf(url) {
        try { var u = new URL(url); return (u.pathname || '/') + (u.search || ''); }
        catch (e) { return url || '/'; }
    }
    function open() { modal.classList.remove('hidden'); }
    function close() { modal.classList.add('hidden'); }

    function render(label, data) {
        var total = data.total_clicks || 0;
        title.textContent = label || '<?php echo esc_js( __( '(no text)', 'kantan-analytics' ) ); ?>';
        sub.textContent = (total === 1
            ? '<?php echo esc_js( __( '%1$s click · last %2$s days', 'kantan-analytics' ) ); ?>'
            : '<?php echo esc_js( __( '%1$s clicks · last %2$s days', 'kantan-analytics' ) ); ?>'
            ).replace('%1$s', total.toLocaleString()).replace('%2$s', days);

        var pages = data.pages || [];
        var rows = pages.map(function(p) {
            return '<div class="flex items-center justify-between gap-2 text-sm py-2 border-b border-gray-50 last:border-0 cursor-pointer hover:bg-gray-50 rounded px-1 -mx-1 kantan-page-link" data-page-url="' + esc(p.page_url) + '" data-page-title="' + esc(p.page_url) + '">' +
                '<span class="text-gray-700 truncate" title="' + esc(p.page_url) + '">' + esc(pathOf(p.page_url)) + '</span>' +
                '<span class="px-2.5 py-0.5 text-xs font-semibold rounded-full bg-orange-100 text-orange-800 flex-shrink-0">' + p.clicks + '</span></div>';
        }).join('');

        body.innerHTML = '<h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2"><?php echo esc_js( __( 'Clicked on these pages', 'kantan-analytics' ) ); ?></h4>' +
            (rows ? '<div class="space-y-1">' + rows + '</div>' : '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No page data.', 'kantan-analytics' ) ); ?></p>');
    }

    document.addEventListener('click', function(e) {
        var row = e.target.closest('.kantan-element-link');
        if (!row) return;
        var text = row.getAttribute('data-element-text') || '';
        title.textContent = text || '<?php echo esc_js( __( '(no text)', 'kantan-analytics' ) ); ?>';
        sub.textContent = '<?php echo esc_js( __( 'Loading…', 'kantan-analytics' ) ); ?>';
        body.innerHTML = '<div class="py-12 text-center text-gray-400"><?php echo esc_js( __( 'Loading element detail…', 'kantan-analytics' ) ); ?></div>';
        open();
        fetch(restBase + '/interactions/element?days=' + days + '&text=' + encodeURIComponent(text), {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) { render(text, data); })
        .catch(function() {
            body.innerHTML = '<div class="py-12 text-center text-red-500"><?php echo esc_js( __( 'Could not load element detail. Please try again.', 'kantan-analytics' ) ); ?></div>';
        });
    });

    document.addEventListener('click', function(e) { if (e.target.closest('[data-element-close]')) close(); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) close(); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== VISITOR HISTORY MODAL ==================== -->
<div id="kantan-visitor-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-visitor-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-2xl" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl z-10">
            <div class="min-w-0 pr-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-purple-600 mb-1"><?php esc_html_e('Visitor', 'kantan-analytics'); ?></p>
                <h3 id="kantan-visitor-title" class="text-xl font-bold text-gray-900 truncate">&nbsp;</h3>
                <p id="kantan-visitor-sub" class="text-sm text-gray-500 mt-0.5"></p>
            </div>
            <button type="button" data-visitor-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div id="kantan-visitor-body" class="p-6"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanVisitorInit) return;
    window.__kantanVisitorInit = true;

    var restBase = '<?php echo esc_url(rest_url('kantan/v1/visitors/')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';

    var modal = document.getElementById('kantan-visitor-modal');
    var title = document.getElementById('kantan-visitor-title');
    var sub   = document.getElementById('kantan-visitor-sub');
    var body  = document.getElementById('kantan-visitor-body');

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }
    function pathOf(url) {
        try { var u = new URL(url); return (u.pathname || '/') + (u.search || ''); }
        catch (e) { return url || '/'; }
    }
    function fmtDur(s) {
        s = parseInt(s, 10) || 0;
        if (s < 60) return s + 's';
        var m = Math.floor(s / 60), r = s % 60;
        return m + 'm' + (r ? ' ' + r + 's' : '');
    }
    function fmtDate(str) {
        if (!str) return '';
        var p = String(str).split(/[ T]/), d = (p[0] || '').split('-'), t = (p[1] || '').split(':');
        var mon = <?php echo $kantan_js_months_json; ?>[parseInt(d[1], 10) - 1] || '';
        var hh = parseInt(t[0] || 0, 10), ap = hh >= 12 ? <?php echo wp_json_encode($kantan_js_ampm['pm']); ?> : <?php echo wp_json_encode($kantan_js_ampm['am']); ?>, h12 = hh % 12 || 12;
        return mon + ' ' + parseInt(d[2], 10) + ', ' + h12 + ':' + (t[1] || '00') + ' ' + ap;
    }
    var SRC_CLS = { organic:'bg-green-100 text-green-700', direct:'bg-gray-100 text-gray-700', social:'bg-purple-100 text-purple-700', referral:'bg-blue-100 text-blue-700', ai:'bg-amber-100 text-amber-700' };

    function open() { modal.classList.remove('hidden'); }
    function close() { modal.classList.add('hidden'); }

    function render(v) {
        title.textContent = v.display_name || '<?php echo esc_js( __( 'Anonymous', 'kantan-analytics' ) ); ?>';
        var n = parseInt(v.total_sessions, 10) || (v.sessions ? v.sessions.length : 0);
        sub.textContent = (n === 1
            ? '<?php echo esc_js( __( '%s session', 'kantan-analytics' ) ); ?>'
            : '<?php echo esc_js( __( '%s sessions', 'kantan-analytics' ) ); ?>'
            ).replace('%s', n) +
            (v.first_seen ? ' · ' + '<?php echo esc_js( __( 'first', 'kantan-analytics' ) ); ?>' + ' ' + fmtDate(v.first_seen) : '') +
            (v.last_seen ? ' · ' + '<?php echo esc_js( __( 'last', 'kantan-analytics' ) ); ?>' + ' ' + fmtDate(v.last_seen) : '');

        var sessions = v.sessions || [];
        if (!sessions.length) { body.innerHTML = '<p class="text-gray-400 italic text-sm"><?php echo esc_js( __( 'No sessions in the last 90 days.', 'kantan-analytics' ) ); ?></p>'; return; }

        body.innerHTML = sessions.map(function(s) {
            var src = (s.traffic_source || 'unknown').toLowerCase();
            var srcCls = SRC_CLS[src] || 'bg-gray-100 text-gray-700';
            var badges = '<span class="' + srcCls + ' px-2 py-0.5 rounded text-xs font-medium capitalize">' + esc(src === 'ai' ? '<?php echo esc_js( __( 'AI assistants', 'kantan-analytics' ) ); ?>' : src) + '</span>';
            if (parseInt(s.is_bounce, 10) === 1) badges += ' <span class="px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded text-xs"><?php echo esc_js( __( 'bounce', 'kantan-analytics' ) ); ?></span>';
            var convs = (s.conversions || []);
            if (convs.length) badges += ' <span class="px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-xs">' + convs.length + ' conv</span>';

            var pages = (s.pages || []).map(function(p, i) {
                var arrow = i > 0 ? '<span class="text-gray-300 mx-1">→</span>' : '';
                var sd = parseInt(p.scroll_depth, 10) || 0;
                return arrow + '<span class="kantan-page-link cursor-pointer hover:text-blue-600 text-gray-700" data-page-url="' + esc(p.page_url) + '" data-page-title="' + esc(p.page_title || p.page_url) + '" title="' + esc(p.page_url) + ' — ' + '<?php echo esc_js( __( 'scrolled %s%', 'kantan-analytics' ) ); ?>'.replace('%s', sd) + '">' + esc(pathOf(p.page_url)) + '</span>';
            }).join('');

            var convRows = convs.map(function(c) {
                return '<div class="text-xs text-green-700 mt-1">✓ ' + esc(c.conversion_type) + (c.conversion_label ? ' — ' + esc(c.conversion_label) : '') + '</div>';
            }).join('');

            return '<div class="border border-gray-100 rounded-lg p-3 mb-3">' +
                '<div class="flex items-center justify-between gap-2 mb-2 flex-wrap">' +
                    '<span class="text-sm font-medium text-gray-800">' + fmtDate(s.visit_date) + '</span>' +
                    '<span class="flex items-center gap-1 flex-wrap">' + badges + '<span class="text-xs text-gray-500 ml-1">' + fmtDur(s.visit_duration) + '</span></span>' +
                '</div>' +
                '<div class="text-sm leading-relaxed">' + (pages || '<span class="text-gray-400 italic text-xs"><?php echo esc_js( __( 'no page detail', 'kantan-analytics' ) ); ?></span>') + '</div>' +
                convRows +
            '</div>';
        }).join('');
    }

    document.addEventListener('click', function(e) {
        var trigger = e.target.closest('.kantan-visitor-history');
        if (!trigger) return;
        e.preventDefault();
        var vid = trigger.getAttribute('data-visitor-id');
        if (!vid) return;
        title.textContent = trigger.textContent || '<?php echo esc_js( __( 'Visitor', 'kantan-analytics' ) ); ?>';
        sub.textContent = '<?php echo esc_js( __( 'Loading…', 'kantan-analytics' ) ); ?>';
        body.innerHTML = '<div class="py-12 text-center text-gray-400"><?php echo esc_js( __( 'Loading visit history…', 'kantan-analytics' ) ); ?></div>';
        open();
        fetch(restBase + encodeURIComponent(vid) + '?days=90', {
            credentials: 'same-origin',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(function(r) { return r.ok ? r.json() : Promise.reject(r); })
        .then(render)
        .catch(function() {
            body.innerHTML = '<div class="py-12 text-center text-red-500"><?php echo esc_js( __( 'Could not load this visitor’s history.', 'kantan-analytics' ) ); ?></div>';
        });
    });

    document.addEventListener('click', function(e) { if (e.target.closest('[data-visitor-close]')) close(); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) close(); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>

<!-- ==================== "WHAT ABOUT CODEX?" MODAL (shared) ==================== -->
<div id="kantan-codex-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-codex-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-lg" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100">
            <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('Using Kantan with OpenAI Codex', 'kantan-analytics'); ?></h3>
            <button type="button" data-codex-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div class="p-6 space-y-3 text-sm text-gray-600 leading-relaxed">
            <p><?php echo wp_kses_post( __( 'Kantan\'s agent is a Markdown file with YAML frontmatter — the format <strong>Claude Code</strong> (<code class="bg-gray-100 px-1 rounded text-xs">.claude/agents/</code>) and <strong>Gemini CLI</strong> (<code class="bg-gray-100 px-1 rounded text-xs">.gemini/agents/</code>) both load as a named, auto-delegating subagent.', 'kantan-analytics' ) ); ?></p>
            <p><?php echo wp_kses_post( __( '<strong>Codex is different.</strong> It defines custom agents as TOML (<code class="bg-gray-100 px-1 rounded text-xs">.codex/agents/*.toml</code>), and as of now it can\'t reliably invoke a custom agent <em>by name</em> inside a tool-backed session. So a clean drop-in install isn\'t dependable on Codex yet — which is why we don\'t list it as officially supported.', 'kantan-analytics' ) ); ?></p>
            <p><?php echo wp_kses_post( __( '<strong>You can still use Kantan with Codex today:</strong> paste the contents of the downloaded <code class="bg-gray-100 px-1 rounded text-xs">.md</code> into your project\'s <code class="bg-gray-100 px-1 rounded text-xs">AGENTS.md</code> (or straight into a prompt). Codex will pick up the API endpoints and workflows — it just won\'t be a named subagent the way it is in Claude Code and Gemini CLI.', 'kantan-analytics' ) ); ?></p>
            <p class="text-gray-500"><?php esc_html_e('We\'ll add official Codex support as soon as named subagent invocation is solid.', 'kantan-analytics'); ?></p>
        </div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanCodexInit) return;
    window.__kantanCodexInit = true;
    var modal = document.getElementById('kantan-codex-modal');
    if (!modal) return;
    document.addEventListener('click', function(e) {
        if (e.target.closest('[data-codex-open]')) { e.preventDefault(); modal.classList.remove('hidden'); return; }
        if (e.target.closest('[data-codex-close]')) { modal.classList.add('hidden'); }
    });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) modal.classList.add('hidden'); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>
