/**
 * Lean Analytics Admin - Modern Dashboard
 */
(function($) {
    'use strict';
    
    var currentRange = 'last_30_days';
    var currentTab = 'overview';
    var allData = {}; // Cache all data
    
    $(document).ready(function() {
        // Check if leanAnalyticsAdmin is defined
        if (typeof leanAnalyticsAdmin === 'undefined') {
            console.error('leanAnalyticsAdmin is not defined! Scripts not loaded properly.');
            $('#lean-content').html('<div class="lean-empty-state"><div class="lean-empty-state-icon"></div><p>Configuration Error: Analytics scripts not loaded properly. Please refresh the page.</p></div>');
            return;
        }

        console.log('Lean Analytics initialized', leanAnalyticsAdmin);

        // Read URL parameters
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('range')) {
            currentRange = urlParams.get('range');
            $('#lean-range-select').val(currentRange);
        }
        if (urlParams.has('tab')) {
            currentTab = urlParams.get('tab');
        }

        // Load initial data
        loadData();
        
        // Range selector
        $('#lean-range-select').on('change', function() {
            currentRange = $(this).val();
            updateURL();
            loadData();
        });
        
        // Tab switching
        $(document).on('click', '.lean-tab', function() {
            $('.lean-tab').removeClass('active');
            $(this).addClass('active');
            currentTab = $(this).data('tab');
            updateURL();
            renderCurrentTab();
        });
        
        // Expand button in cards
        $(document).on('click', '.lean-expand-btn', function() {
            var tab = $(this).data('tab');
            $('.lean-tab').removeClass('active');
            $('.lean-tab[data-tab="' + tab + '"]').addClass('active');
            currentTab = tab;
            updateURL();
            renderCurrentTab();
        });
        
        // Settings toggle
        $('#lean-settings-btn').on('click', function() {
            $('#lean-settings-panel').slideToggle(300);
        });
        
        // Cleanup preview - toggle show/hide
        $('#lean-cleanup-preview').on('click', function() {
            var $result = $('#lean-cleanup-result');

            // If result is visible and has content, hide it
            if ($result.is(':visible') && $result.html().trim() !== '') {
                $result.slideUp(200);
                return;
            }

            var cutoff = $('#lean-cleanup-date').val();
            if (!cutoff) {
                alert('Please select a date');
                return;
            }
            previewCleanup(cutoff);
        });
        
        // Cleanup execute
        $('#lean-cleanup-execute').on('click', function() {
            var cutoff = $('#lean-cleanup-date').val();
            if (!cutoff) {
                alert('Please select a date');
                return;
            }
            
            if (!confirm('Are you sure you want to delete all data before ' + cutoff + '? This cannot be undone.')) {
                return;
            }
            
            executeCleanup(cutoff);
        });
    });
    
    function updateURL() {
        var url = new URL(window.location);
        url.searchParams.set('range', currentRange);
        url.searchParams.set('tab', currentTab);
        window.history.pushState({}, '', url);
    }
    
    function loadData() {
        $('#lean-content').html('<div class="lean-loading"><svg class="lean-spinner" width="40" height="40" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke-width="4" stroke="currentColor" stroke-dasharray="31.4 31.4" stroke-linecap="round"><animateTransform attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="1s" repeatCount="indefinite"/></circle></svg><p>Loading analytics...</p></div>');

        // Load all data at once including real-time
        var requests = {
            overview: loadMetric('overview'),
            pages: loadMetric('pages'),
            referrers: loadMetric('referrers'),
            countries: loadMetric('countries'),
            posts: loadMetric('posts'),
            other_content: loadMetric('other_content'),
            hourly: loadMetric('hourly'),
            campaigns: loadMetric('campaigns'),
            entry_pages: loadMetric('entry_pages'),
            exit_pages: loadMetric('exit_pages'),
            realtime: loadRealTimeMetric()
        };

        // Use Promise.allSettled pattern to handle partial failures gracefully
        $.when(
            requests.overview.then(null, function() { return {data: null}; }),
            requests.pages.then(null, function() { return {data: []}; }),
            requests.referrers.then(null, function() { return {data: []}; }),
            requests.countries.then(null, function() { return {data: []}; }),
            requests.posts.then(null, function() { return {data: []}; }),
            requests.other_content.then(null, function() { return {data: []}; }),
            requests.hourly.then(null, function() { return {data: []}; }),
            requests.campaigns.then(null, function() { return {data: []}; }),
            requests.entry_pages.then(null, function() { return {data: []}; }),
            requests.exit_pages.then(null, function() { return {data: []}; }),
            requests.realtime.then(null, function() { return {data: {active_visitors: 0, active_pages: []}}; })
        )
            .done(function(overviewRes, pagesRes, referrersRes, countriesRes, postsRes, otherContentRes, hourlyRes, campaignsRes, entryRes, exitRes, realtimeRes) {
                allData = {
                    overview: (overviewRes[0] && overviewRes[0].data) || {stats: {}, series: [], devices: []},
                    pages: (pagesRes[0] && pagesRes[0].data) || [],
                    referrers: (referrersRes[0] && referrersRes[0].data) || [],
                    countries: (countriesRes[0] && countriesRes[0].data) || [],
                    posts: (postsRes[0] && postsRes[0].data) || [],
                    other_content: (otherContentRes[0] && otherContentRes[0].data) || [],
                    hourly: (hourlyRes[0] && hourlyRes[0].data) || [],
                    campaigns: (campaignsRes[0] && campaignsRes[0].data) || [],
                    entry_pages: (entryRes[0] && entryRes[0].data) || [],
                    exit_pages: (exitRes[0] && exitRes[0].data) || [],
                    realtime: (realtimeRes[0] && realtimeRes[0].data) || {active_visitors: 0, active_pages: []}
                };
                renderCurrentTab();

                // Start real-time auto-refresh for overview tab
                if (currentTab === 'overview') {
                    startRealtimeRefresh();
                }
            })
            .fail(function(error) {
                console.error('Analytics loading error:', error);
                $('#lean-content').html('<div class="lean-empty-state"><div class="lean-empty-state-icon"></div><p>Error loading data. Check browser console for details.</p></div>');
            });
    }
    
    function loadMetric(metric) {
        return $.ajax({
            url: leanAnalyticsAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'lean_analytics_data',
                nonce: leanAnalyticsAdmin.nonce,
                range: currentRange,
                metric: metric
            }
        }).fail(function(xhr, status, error) {
            console.error('Failed to load metric "' + metric + '":', status, error, xhr.responseText);
        });
    }
    
    function renderCurrentTab() {
        var html = '';
        
        // Update active tab
        $('.lean-tab').removeClass('active');
        $('.lean-tab[data-tab="' + currentTab + '"]').addClass('active');
        
        switch (currentTab) {
            case 'overview':
                html = renderOverview();
                startRealtimeRefresh(); // Auto-refresh real-time widget
                break;
            case 'pages':
                html = renderFullPages();
                break;
            case 'referrers':
                html = renderFullReferrers();
                break;
            case 'countries':
                html = renderFullCountries();
                break;
            case 'posts':
                html = renderFullPosts();
                break;
            case 'other_content':
                html = renderFullOtherContent();
                break;
            case 'hourly':
                html = renderFullHourly();
                break;
            case 'campaigns':
                html = renderFullCampaigns();
                break;
            case 'entry_pages':
                html = renderFullEntryPages();
                break;
            case 'exit_pages':
                html = renderFullExitPages();
                break;
        }

        $('#lean-content').html(html);
    }
    
    function renderOverview() {
        var data = allData.overview;
        var html = '';

        // Stats Cards - Now with 6 metrics including real-time
        html += '<div class="lean-stats-grid lean-stats-grid-6">';

        if (data.stats) {
            // Real-time visitors card - FIRST
            var realtimeCount = allData.realtime ? allData.realtime.active_visitors : 0;
            html += renderRealtimeStatCard('Active Now', formatNumber(realtimeCount), '');

            html += renderStatCard('Pageviews', formatNumber(data.stats.pageviews), '');
            html += renderStatCard('Visits', formatNumber(data.stats.visits), '');
            html += renderStatCard('Unique Visitors', formatNumber(data.stats.unique_visitors), '');
            html += renderStatCard('Bounce Rate', data.stats.bounce_rate + '%', '');
            html += renderStatCard('Pages/Visit', data.stats.pages_per_visit, '');
        }

        html += '</div>';

        // Daily Trend Chart (hourly for today/yesterday)
        if (currentRange === 'today' || currentRange === 'yesterday') {
            html += renderHourlyChart(allData.hourly);
        } else {
            html += renderChart(data.series);
        }

        // Row 1: Top Pages, Top Posts, and Active Pages (3 columns)
        html += '<div class="lean-data-grid lean-data-grid-3col">';
        html += renderPagesCard('Top Pages', 'pages', allData.pages);
        html += renderPostsCard('Top Posts', 'posts', allData.posts);
        html += renderActivePagesCard('Active Pages', allData.realtime);
        html += '</div>';

        // Row 2: Referrers, Countries, Devices (3 columns)
        html += '<div class="lean-data-grid lean-data-grid-3col">';
        html += renderDataCard('Top Referrers', 'referrers', allData.referrers, ['ref_domain', 'Domain']);
        html += renderDataCard('Top Countries', 'countries', allData.countries, ['country_code', 'Country']);
        html += renderDevicesCard(data.devices);
        html += '</div>';

        // Row 3: UTM Campaigns, Entry Pages, Exit Pages (3 columns)
        html += '<div class="lean-data-grid lean-data-grid-3col">';
        html += renderCampaignsCard('UTM Campaigns', 'campaigns', allData.campaigns);
        html += renderEntryPagesCard('Entry Pages', 'entry_pages', allData.entry_pages);
        html += renderExitPagesCard('Exit Pages', 'exit_pages', allData.exit_pages);
        html += '</div>';

        // Note: Other Content is NOT shown on dashboard overview - only in its dedicated tab

        return html;
    }
    
    function renderEmptyStateWithInfo(icon, title, description) {
        var html = '<div class="lean-empty-state">';
        html += '<div class="lean-empty-state-icon">' + icon + '</div>';
        html += '<p><strong>' + title + '</strong></p>';
        if (description) {
            html += '<p style="max-width: 400px; margin: 10px auto 0; color: var(--gray-500, #64748b); font-size: 13px; line-height: 1.6;">' + description + '</p>';
        }
        html += '</div>';
        return html;
    }

    function renderFullPages() {
        var data = allData.pages;
        var html = '<div class="lean-full-table-container">';

        if (!data || data.length === 0) {
            html += renderEmptyStateWithInfo('', 'No page data available', 'Page views will appear here once visitors start browsing your site. Analytics tracking is automatic for all WordPress pages.');
        } else {
            html += '<table class="lean-table">';
            html += '<thead><tr><th>Path</th><th class="lean-number">Pageviews</th><th class="lean-number">Visits</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(function(row) {
                html += '<tr>';
                var displayPath = formatPath(row.path);
                if (row.page_url) {
                    html += '<td><a href="' + escapeHtml(row.page_url) + '" target="_blank" class="lean-path">' + escapeHtml(displayPath) + '</a></td>';
                } else {
                    html += '<td><span class="lean-path">' + escapeHtml(displayPath) + '</span></td>';
                }
                html += '<td class="lean-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        return html;
    }
    
    function renderFullReferrers() {
        var data = allData.referrers;
        var html = '<div class="lean-full-table-container">';

        if (!data || data.length === 0) {
            html += renderEmptyStateWithInfo('', 'No referrer data available', 'Referrers show where your visitors come from (search engines, social media, other websites). Data appears when visitors arrive from external links.');
        } else {
            html += '<table class="lean-table">';
            html += '<thead><tr><th>Domain</th><th class="lean-number">Pageviews</th><th class="lean-number">Visits</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(function(row) {
                html += '<tr>';
                html += '<td>' + escapeHtml(row.ref_domain) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        return html;
    }
    
    function renderFullCountries() {
        var data = allData.countries;
        var html = '<div class="lean-full-table-container">';

        if (!data || data.length === 0) {
            html += '<div class="lean-empty-state">';
            html += '<div class="lean-empty-state-icon"></div>';
            html += '<p><strong>No country data available</strong></p>';
            html += '<div class="lean-info-box" style="max-width: 500px; margin: 20px auto; text-align: left; background: var(--gray-50); border: 1px solid var(--gray-200); border-radius: 8px; padding: 16px;">';
            html += '<p style="margin: 0 0 12px 0; color: var(--gray-600);"><strong>How to enable country tracking:</strong></p>';
            html += '<ol style="margin: 0; padding-left: 20px; color: var(--gray-600); line-height: 1.8;">';
            html += '<li>Use <strong>Cloudflare</strong> as your CDN/proxy</li>';
            html += '<li>Enable the <code style="background: var(--gray-200); padding: 2px 6px; border-radius: 4px;">CF-IPCountry</code> header in Cloudflare settings</li>';
            html += '<li>Switchboard will automatically detect and log visitor countries</li>';
            html += '</ol>';
            html += '<p style="margin: 12px 0 0 0; font-size: 12px; color: var(--gray-500);">Country data is privacy-friendly - only the country code is stored, not visitor IPs.</p>';
            html += '</div>';
            html += '</div>';
        } else {
            html += '<table class="lean-table">';
            html += '<thead><tr><th>Country Code</th><th class="lean-number">Pageviews</th><th class="lean-number">Visits</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(function(row) {
                html += '<tr>';
                html += '<td>' + escapeHtml(row.country_code) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        return html;
    }
    
    function renderFullPosts() {
        var data = allData.posts;
        var html = '<div class="lean-full-table-container">';

        if (!data || data.length === 0) {
            html += renderEmptyStateWithInfo('', 'No post data available', 'Blog post views will appear here. This tracks views specifically for posts (post_type = "post"), not pages or custom post types.');
        } else {
            html += '<table class="lean-table">';
            html += '<thead><tr><th>Title</th><th class="lean-number">Pageviews</th><th class="lean-number">Visits</th></tr></thead>';
            html += '<tbody>';

            data.forEach(function(row) {
                html += '<tr>';
                if (row.post_url) {
                    html += '<td><a href="' + escapeHtml(row.post_url) + '" target="_blank" class="lean-post-link">' + escapeHtml(row.post_title) + '</a></td>';
                } else {
                    html += '<td>' + escapeHtml(row.post_title) + '</td>';
                }
                html += '<td class="lean-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });

            html += '</tbody></table>';
        }

        html += '</div>';
        return html;
    }

    function renderFullOtherContent() {
        var data = allData.other_content;
        var html = '<div class="lean-full-table-container">';

        if (!data || data.length === 0) {
            html += renderEmptyStateWithInfo('', 'No custom post type data available', 'This section shows views for custom post types (CPTs) like products, portfolios, events, etc. If you have CPTs registered, their views will appear here once visitors access them.');
        } else {
            html += '<table class="lean-table">';
            html += '<thead><tr><th>Title</th><th>Type</th><th class="lean-number">Pageviews</th><th class="lean-number">Visits</th></tr></thead>';
            html += '<tbody>';

            data.forEach(function(row) {
                html += '<tr>';
                if (row.post_url) {
                    html += '<td><a href="' + escapeHtml(row.post_url) + '" target="_blank" class="lean-post-link">' + escapeHtml(row.post_title) + '</a></td>';
                } else {
                    html += '<td>' + escapeHtml(row.post_title) + '</td>';
                }
                html += '<td>' + escapeHtml(row.post_type_label || row.post_type) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });

            html += '</tbody></table>';
        }

        html += '</div>';
        return html;
    }

    function renderOtherContentCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + title + '</h3>';
        html += '<button class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
        html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
        html += '<polyline points="9 18 15 12 9 6"></polyline>';
        html += '</svg>';
        html += '</button>';
        html += '</div>';
        html += '<div class="lean-data-card-body">';

        if (!data || data.length === 0) {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No data</p></div>';
        } else {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Title</th>';
            html += '<th>Type</th>';
            html += '<th class="lean-mini-number">Views</th>';
            html += '<th class="lean-mini-number">Visits</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            data.slice(0, 10).forEach(function(row) {
                html += '<tr>';
                var displayTitle = truncate(row.post_title, 25);
                if (row.post_url) {
                    html += '<td class="lean-label" title="' + escapeHtml(row.post_title) + '"><a href="' + escapeHtml(row.post_url) + '" target="_blank" class="lean-table-link">' + escapeHtml(displayTitle) + '</a></td>';
                } else {
                    html += '<td class="lean-label" title="' + escapeHtml(row.post_title) + '">' + escapeHtml(displayTitle) + '</td>';
                }
                html += '<td class="lean-label">' + escapeHtml(row.post_type_label || row.post_type) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });

            html += '</tbody></table>';
        }

        html += '</div>';
        html += '</div>';

        return html;
    }

    function renderFullHourly() {
        var html = renderHourlyChart(allData.hourly);
        return html;
    }
    
    function renderStatCard(label, value, icon) {
        return '<div class="lean-stat-card">' +
            '<div class="lean-stat-label">' + icon + ' ' + label + '</div>' +
            '<div class="lean-stat-value">' + value + '</div>' +
            '</div>';
    }
    
    function renderPagesCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + title + '</h3>';
        html += '<button class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
        html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
        html += '<polyline points="9 18 15 12 9 6"></polyline>';
        html += '</svg>';
        html += '</button>';
        html += '</div>';
        html += '<div class="lean-data-card-body">';
        
        if (!data || data.length === 0) {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No data</p></div>';
        } else {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Path</th>';
            html += '<th class="lean-mini-number">Views</th>';
            html += '<th class="lean-mini-number">Visits</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            
            data.slice(0, 10).forEach(function(row) {
                html += '<tr>';
                var displayPath = truncate(formatPath(row.path), 30);
                var titlePath = formatPath(row.path);
                if (row.page_url) {
                    html += '<td class="lean-label" title="' + escapeHtml(titlePath) + '"><a href="' + escapeHtml(row.page_url) + '" target="_blank" class="lean-table-link">' + escapeHtml(displayPath) + '</a></td>';
                } else {
                    html += '<td class="lean-label" title="' + escapeHtml(titlePath) + '">' + escapeHtml(displayPath) + '</td>';
                }
                html += '<td class="lean-mini-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        html += '</div>';
        
        return html;
    }
    
    function renderPostsCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + title + '</h3>';
        html += '<button class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
        html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
        html += '<polyline points="9 18 15 12 9 6"></polyline>';
        html += '</svg>';
        html += '</button>';
        html += '</div>';
        html += '<div class="lean-data-card-body">';
        
        if (!data || data.length === 0) {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No data</p></div>';
        } else {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Title</th>';
            html += '<th class="lean-mini-number">Views</th>';
            html += '<th class="lean-mini-number">Visits</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            
            data.slice(0, 10).forEach(function(row) {
                html += '<tr>';
                var displayTitle = truncate(row.post_title, 30);
                if (row.post_url) {
                    html += '<td class="lean-label" title="' + escapeHtml(row.post_title) + '"><a href="' + escapeHtml(row.post_url) + '" target="_blank" class="lean-table-link">' + escapeHtml(displayTitle) + '</a></td>';
                } else {
                    html += '<td class="lean-label" title="' + escapeHtml(row.post_title) + '">' + escapeHtml(displayTitle) + '</td>';
                }
                html += '<td class="lean-mini-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        html += '</div>';
        
        return html;
    }
    
    function renderDataCard(title, tabName, data, fieldConfig) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + title + '</h3>';
        html += '<button class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
        html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
        html += '<polyline points="9 18 15 12 9 6"></polyline>';
        html += '</svg>';
        html += '</button>';
        html += '</div>';
        html += '<div class="lean-data-card-body">';
        
        if (!data || data.length === 0) {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No data</p></div>';
        } else {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>' + fieldConfig[1] + '</th>';
            html += '<th class="lean-mini-number">Views</th>';
            html += '<th class="lean-mini-number">Visits</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            
            var fieldName = fieldConfig[0];
            data.slice(0, 10).forEach(function(row) {
                html += '<tr>';
                var label = row[fieldName];
                if (fieldName === 'path') {
                    label = truncate(label, 30);
                }
                html += '<td class="lean-label" title="' + escapeHtml(row[fieldName]) + '">' + escapeHtml(label) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        html += '</div>';
        
        return html;
    }
    
    function renderDevicesCard(devices) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>Devices</h3>';
        html += '</div>';
        html += '<div class="lean-data-card-body">';
        
        if (!devices || devices.length === 0) {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No data</p></div>';
        } else {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Device</th>';
            html += '<th class="lean-mini-number">Count</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            
            // Order: Desktop, Mobile, Tablet
            var deviceOrder = ['desktop', 'mobile', 'tablet'];
            var deviceIcons = {'desktop': '', 'mobile': '', 'tablet': ''};
            
            deviceOrder.forEach(function(deviceType) {
                var deviceData = devices.find(function(d) { return d.device === deviceType; });
                if (deviceData) {
                    html += '<tr>';
                    html += '<td class="lean-label">' + deviceIcons[deviceType] + ' ' + capitalize(deviceType) + '</td>';
                    html += '<td class="lean-mini-number">' + formatNumber(deviceData.count) + '</td>';
                    html += '</tr>';
                }
            });
            
            html += '</tbody></table>';
        }
        
        html += '</div>';
        html += '</div>';
        
        return html;
    }
    
    function renderChart(series) {
        if (!series || series.length === 0) {
            return '<div class="lean-chart-container"><div class="lean-chart-empty">No data available for this date range</div></div>';
        }
        
        // Fill in missing days with 0 data
        var filledSeries = fillMissingDays(series);
        
        // Find max value for scaling
        var maxPageviews = 0;
        var maxVisits = 0;
        filledSeries.forEach(function(row) {
            var pv = parseInt(row.pageviews) || 0;
            var v = parseInt(row.visits) || 0;
            maxPageviews = Math.max(maxPageviews, pv);
            maxVisits = Math.max(maxVisits, v);
        });
        var maxValue = Math.max(maxPageviews, maxVisits);
        
        if (maxValue === 0) {
            maxValue = 1; // Prevent division by zero
        }
        
        var html = '<div class="lean-chart-container">';
        
        // Chart Header with Legend
        html += '<div class="lean-chart-header">';
        html += '<h3>Traffic Overview</h3>';
        html += '<div class="lean-chart-legend">';
        html += '<div class="lean-chart-legend-item">';
        html += '<div class="lean-chart-legend-color pageviews"></div>';
        html += '<span>Pageviews</span>';
        html += '</div>';
        html += '<div class="lean-chart-legend-item">';
        html += '<div class="lean-chart-legend-color visits"></div>';
        html += '<span>Visits</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        
        // Chart
        html += '<div class="lean-chart">';
        
        // Y-axis
        html += renderYAxis(maxValue);
        
        // Grid lines
        html += renderGridLines();
        
        // Limit to reasonable number of bars for readability
        var chartData = filledSeries;
        if (filledSeries.length > 30) {
            chartData = filledSeries.slice(-30); // Last 30 days max
        }
        
        chartData.forEach(function(row) {
            var pageviews = parseInt(row.pageviews) || 0;
            var visits = parseInt(row.visits) || 0;
            
            var pageviewsHeight = (pageviews / maxValue) * 100;
            var visitsHeight = (visits / maxValue) * 100;
            
            // Minimum height for visibility
            if (pageviews > 0 && pageviewsHeight < 2) pageviewsHeight = 2;
            if (visits > 0 && visitsHeight < 2) visitsHeight = 2;
            
            html += '<div class="lean-chart-bar-group">';
            
            // Tooltip
            html += '<div class="lean-chart-tooltip">';
            html += '<strong>' + formatDate(row.date) + '</strong><br>';
            html += 'Pageviews: ' + formatNumber(pageviews) + '<br>';
            html += 'Visits: ' + formatNumber(visits);
            html += '</div>';
            
            // Bars container
            html += '<div class="lean-chart-bars">';
            
            // Pageviews bar
            html += '<div class="lean-chart-bar pageviews" style="height: ' + pageviewsHeight + '%"></div>';
            
            // Visits bar
            html += '<div class="lean-chart-bar visits" style="height: ' + visitsHeight + '%"></div>';
            
            html += '</div>';
            
            // Date label (show every 3rd label if > 15 days to avoid crowding)
            var showLabel = chartData.length <= 15 || (chartData.indexOf(row) % 3 === 0);
            if (showLabel) {
                html += '<div class="lean-chart-label">' + formatDateShort(row.date) + '</div>';
            } else {
                html += '<div class="lean-chart-label"></div>';
            }
            
            html += '</div>';
        });
        
        html += '</div>'; // End chart
        html += '</div>'; // End container
        
        return html;
    }
    
    function renderHourlyChart(hourlyData) {
        var html = '<div class="lean-chart-container">';
        html += '<div class="lean-chart-header">';
        html += '<h3>Hourly Traffic</h3>';
        html += '<div class="lean-chart-legend">';
        html += '<div class="lean-chart-legend-item">';
        html += '<div class="lean-chart-legend-color pageviews"></div>';
        html += '<span>Pageviews</span>';
        html += '</div>';
        html += '<div class="lean-chart-legend-item">';
        html += '<div class="lean-chart-legend-color visits"></div>';
        html += '<span>Visits</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        
        // Fill in all 24 hours
        var filledHours = fillMissingHours(hourlyData);
        
        // Find max value
        var maxPageviews = 0;
        var maxVisits = 0;
        filledHours.forEach(function(row) {
            maxPageviews = Math.max(maxPageviews, parseInt(row.pageviews) || 0);
            maxVisits = Math.max(maxVisits, parseInt(row.visits) || 0);
        });
        var maxValue = Math.max(maxPageviews, maxVisits);
        if (maxValue === 0) maxValue = 1;
        
        html += '<div class="lean-chart">';
        
        // Y-axis
        html += renderYAxis(maxValue);
        
        // Grid lines
        html += renderGridLines();
        
        filledHours.forEach(function(row) {
            var pageviews = parseInt(row.pageviews) || 0;
            var visits = parseInt(row.visits) || 0;
            
            var pageviewsHeight = (pageviews / maxValue) * 100;
            var visitsHeight = (visits / maxValue) * 100;
            
            if (pageviews > 0 && pageviewsHeight < 2) pageviewsHeight = 2;
            if (visits > 0 && visitsHeight < 2) visitsHeight = 2;
            
            html += '<div class="lean-chart-bar-group">';
            
            html += '<div class="lean-chart-tooltip">';
            html += '<strong>' + formatHour(row.hour) + '</strong><br>';
            html += 'Pageviews: ' + formatNumber(pageviews) + '<br>';
            html += 'Visits: ' + formatNumber(visits);
            html += '</div>';
            
            html += '<div class="lean-chart-bars">';
            html += '<div class="lean-chart-bar pageviews" style="height: ' + pageviewsHeight + '%"></div>';
            html += '<div class="lean-chart-bar visits" style="height: ' + visitsHeight + '%"></div>';
            html += '</div>';
            
            // Show hour labels for every 2nd hour to avoid crowding
            if (row.hour % 2 === 0) {
                html += '<div class="lean-chart-label">' + formatHourShort(row.hour) + '</div>';
            } else {
                html += '<div class="lean-chart-label"></div>';
            }
            
            html += '</div>';
        });
        
        html += '</div>';
        html += '</div>';
        
        return html;
    }
    
    function fillMissingDays(series) {
        if (!series || series.length === 0) {
            return generateDateRange();
        }
        
        var dateRange = getDateRangeFromSelection();
        var dataMap = {};
        
        // Create map of existing data
        series.forEach(function(row) {
            dataMap[row.date] = row;
        });
        
        // Fill in missing days
        var filled = [];
        var currentDate = new Date(dateRange.from);
        var endDate = new Date(dateRange.to);
        
        while (currentDate <= endDate) {
            var dateStr = currentDate.toISOString().split('T')[0];
            if (dataMap[dateStr]) {
                filled.push(dataMap[dateStr]);
            } else {
                filled.push({
                    date: dateStr,
                    pageviews: 0,
                    visits: 0
                });
            }
            currentDate.setDate(currentDate.getDate() + 1);
        }
        
        return filled;
    }
    
    function fillMissingHours(hourlyData) {
        var dataMap = {};
        
        if (hourlyData) {
            hourlyData.forEach(function(row) {
                dataMap[parseInt(row.hour)] = row;
            });
        }
        
        var filled = [];
        for (var hour = 0; hour < 24; hour++) {
            if (dataMap[hour]) {
                filled.push(dataMap[hour]);
            } else {
                filled.push({
                    hour: hour,
                    pageviews: 0,
                    visits: 0
                });
            }
        }
        
        return filled;
    }
    
    function generateDateRange() {
        var range = getDateRangeFromSelection();
        var filled = [];
        var currentDate = new Date(range.from);
        var endDate = new Date(range.to);
        
        while (currentDate <= endDate) {
            filled.push({
                date: currentDate.toISOString().split('T')[0],
                pageviews: 0,
                visits: 0
            });
            currentDate.setDate(currentDate.getDate() + 1);
        }
        
        return filled;
    }
    
    function getDateRangeFromSelection() {
        var today = new Date();
        today.setHours(0, 0, 0, 0);
        var from = new Date(today);
        var to = new Date(today);
        
        switch (currentRange) {
            case 'today':
                break;
            case 'yesterday':
                from.setDate(from.getDate() - 1);
                to.setDate(to.getDate() - 1);
                break;
            case 'this_week':
                var day = from.getDay();
                var diff = from.getDate() - day + (day === 0 ? -6 : 1);
                from.setDate(diff);
                break;
            case 'last_week':
                var day = from.getDay();
                var diff = from.getDate() - day + (day === 0 ? -6 : 1) - 7;
                from.setDate(diff);
                to = new Date(from);
                to.setDate(to.getDate() + 6);
                break;
            case 'this_month':
                from.setDate(1);
                break;
            case 'last_month':
                from.setMonth(from.getMonth() - 1);
                from.setDate(1);
                to = new Date(from.getFullYear(), from.getMonth() + 1, 0);
                break;
            case 'last_30_days':
                from.setDate(from.getDate() - 30);
                break;
            case 'last_90_days':
                from.setDate(from.getDate() - 90);
                break;
            case 'last_365_days':
                from.setDate(from.getDate() - 365);
                break;
            case 'this_year':
                from.setMonth(0);
                from.setDate(1);
                break;
            case 'last_year':
                from.setFullYear(from.getFullYear() - 1);
                from.setMonth(0);
                from.setDate(1);
                to.setFullYear(to.getFullYear() - 1);
                to.setMonth(11);
                to.setDate(31);
                break;
        }
        
        return {
            from: from.toISOString().split('T')[0],
            to: to.toISOString().split('T')[0]
        };
    }
    
    function previewCleanup(cutoff) {
        var $result = $('#lean-cleanup-result');
        $result.hide().html('Loading...');

        $.ajax({
            url: leanAnalyticsAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'lean_analytics_cleanup',
                nonce: leanAnalyticsAdmin.nonce,
                cleanup_action: 'preview',
                cutoff: cutoff
            },
            success: function(response) {
                if (response.success) {
                    var html = '<strong>Preview:</strong> ';
                    html += formatNumber(response.data.count) + ' events will be deleted ';
                    html += '(~' + response.data.size_mb + ' MB)';
                    $result.html(html).slideDown(200);
                } else {
                    $result.html('<span style="color: var(--red-500, #ef4444);">Error: ' + response.data + '</span>').slideDown(200);
                }
            }
        });
    }
    
    function executeCleanup(cutoff) {
        var $result = $('#lean-cleanup-result');
        $result.html('Deleting data...').slideDown(200);

        $.ajax({
            url: leanAnalyticsAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'lean_analytics_cleanup',
                nonce: leanAnalyticsAdmin.nonce,
                cleanup_action: 'execute',
                cutoff: cutoff
            },
            success: function(response) {
                if (response.success) {
                    $result.html('<span style="color: var(--lean-success, #10b981);">Deleted ' + formatNumber(response.data.deleted) + ' events</span>');
                    // Reload data and hide result after delay
                    setTimeout(function() {
                        $result.slideUp(200);
                        loadData();
                    }, 2000);
                } else {
                    $result.html('<span style="color: var(--red-500, #ef4444);">Error: ' + response.data + '</span>');
                }
            }
        });
    }
    
    function formatNumber(num) {
        if (!num) return '0';
        return parseInt(num).toLocaleString();
    }
    
    function formatDate(dateStr) {
        var date = new Date(dateStr);
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        return months[date.getMonth()] + ' ' + date.getDate();
    }
    
    function formatDateShort(dateStr) {
        var date = new Date(dateStr);
        return (date.getMonth() + 1) + '/' + date.getDate();
    }
    
    function formatHour(hour) {
        hour = parseInt(hour);
        if (hour === 0) return '12 AM';
        if (hour < 12) return hour + ' AM';
        if (hour === 12) return '12 PM';
        return (hour - 12) + ' PM';
    }
    
    function formatHourShort(hour) {
        hour = parseInt(hour);
        if (hour === 0) return '12a';
        if (hour < 12) return hour + 'a';
        if (hour === 12) return '12p';
        return (hour - 12) + 'p';
    }
    
    function truncate(str, length) {
        if (!str) return '';
        if (str.length <= length) return str;
        return str.substring(0, length) + '...';
    }

    function formatPath(path) {
        if (!path) return '';
        if (path === '/' || path === '') return 'Homepage';
        return path;
    }

    function capitalize(str) {
        if (!str) return '';
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
    
    function renderYAxis(maxValue) {
        var html = '<div class="lean-chart-y-axis">';
        
        // Calculate nice intervals (5 steps)
        var step = Math.ceil(maxValue / 5);
        
        for (var i = 5; i >= 0; i--) {
            var value = step * i;
            html += '<div class="lean-chart-y-label">' + formatNumber(value) + '</div>';
        }
        
        html += '</div>';
        return html;
    }
    
    function renderGridLines() {
        var html = '<div class="lean-chart-grid">';
        
        // 5 grid lines (matching Y-axis)
        for (var i = 0; i <= 5; i++) {
            var position = (i * 20); // 0%, 20%, 40%, 60%, 80%, 100%
            html += '<div class="lean-chart-grid-line" style="top: ' + position + '%"></div>';
        }
        
        html += '</div>';
        return html;
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // UTM Campaigns Card
    function renderCampaignsCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + escapeHtml(title) + '</h3>';
        if (data && data.length > 0) {
            html += '<button type="button" class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
            html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
            html += '<polyline points="15 3 21 3 21 9"></polyline>';
            html += '<polyline points="9 21 3 21 3 15"></polyline>';
            html += '<line x1="21" y1="3" x2="14" y2="10"></line>';
            html += '<line x1="3" y1="21" x2="10" y2="14"></line>';
            html += '</svg>';
            html += '</button>';
        }
        html += '</div>';
        
        if (data && data.length > 0) {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr><th>Campaign</th><th>Views</th><th>Visits</th></tr></thead>';
            html += '<tbody>';
            
            var limited = data.slice(0, 10);
            limited.forEach(function(row) {
                var label = [];
                if (row.utm_campaign) label.push(row.utm_campaign);
                if (row.utm_source) label.push('(' + row.utm_source + ')');
                if (row.utm_medium) label.push('[' + row.utm_medium + ']');
                
                html += '<tr>';
                html += '<td class="lean-label">' + escapeHtml(label.join(' ') || 'Unknown') + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.pageviews) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
        } else {
            var siteUrl = (leanAnalyticsAdmin && leanAnalyticsAdmin.siteUrl) ? leanAnalyticsAdmin.siteUrl : 'yoursite.com';
            html += '<div class="lean-empty-state" style="padding: 20px;"><div class="lean-empty-state-icon" style="font-size: 28px;"></div><p style="margin: 8px 0 0;">No UTM campaigns</p><p style="font-size: 11px; color: var(--gray-400, #94a3b8); margin: 4px 0 0;">' + escapeHtml(siteUrl) + '/?utm_source=...</p></div>';
        }

        html += '</div>';
        return html;
    }

    // Entry Pages Card
    function renderEntryPagesCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + escapeHtml(title) + '</h3>';
        if (data && data.length > 0) {
            html += '<button type="button" class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
            html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
            html += '<polyline points="15 3 21 3 21 9"></polyline>';
            html += '<polyline points="9 21 3 21 3 15"></polyline>';
            html += '<line x1="21" y1="3" x2="14" y2="10"></line>';
            html += '<line x1="3" y1="21" x2="10" y2="14"></line>';
            html += '</svg>';
            html += '</button>';
        }
        html += '</div>';
        
        if (data && data.length > 0) {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr><th>Page</th><th>Entries</th><th>New</th></tr></thead>';
            html += '<tbody>';
            
            var limited = data.slice(0, 10);
            limited.forEach(function(row) {
                html += '<tr>';
                html += '<td class="lean-label"><a href="' + escapeHtml(row.path) + '" class="lean-path" target="_blank">' + escapeHtml(truncate(formatPath(row.path), 40)) + '</a></td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.entries) + '</td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.new_visitors) + '</td>';
                html += '</tr>';
            });

            html += '</tbody>';
            html += '</table>';
        } else {
            html += '<div class="lean-empty-state"><div class="lean-empty-state-icon">🚪</div><p>No entry data</p></div>';
        }

        html += '</div>';
        return html;
    }

    // Exit Pages Card
    function renderExitPagesCard(title, tabName, data) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + escapeHtml(title) + '</h3>';
        if (data && data.length > 0) {
            html += '<button type="button" class="lean-expand-btn" data-tab="' + tabName + '" title="View all">';
            html += '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
            html += '<polyline points="15 3 21 3 21 9"></polyline>';
            html += '<polyline points="9 21 3 21 3 15"></polyline>';
            html += '<line x1="21" y1="3" x2="14" y2="10"></line>';
            html += '<line x1="3" y1="21" x2="10" y2="14"></line>';
            html += '</svg>';
            html += '</button>';
        }
        html += '</div>';

        if (data && data.length > 0) {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr><th>Page</th><th>Exits</th></tr></thead>';
            html += '<tbody>';

            var limited = data.slice(0, 10);
            limited.forEach(function(row) {
                html += '<tr>';
                html += '<td class="lean-label"><a href="' + escapeHtml(row.path) + '" class="lean-path" target="_blank">' + escapeHtml(truncate(formatPath(row.path), 40)) + '</a></td>';
                html += '<td class="lean-mini-number">' + formatNumber(row.exits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
        } else {
            html += '<div class="lean-empty-state"><div class="lean-empty-state-icon">🚪</div><p>No exit data</p></div>';
        }
        
        html += '</div>';
        return html;
    }
    
    // Full Campaigns Tab
    function renderFullCampaigns() {
        var data = allData.campaigns;
        var html = '<div class="lean-full-table-container">';
        
        html += '<h2>UTM Campaigns</h2>';
        
        if (data && data.length > 0) {
            html += '<table class="lean-full-table">';
            html += '<thead><tr><th>Campaign</th><th>Source</th><th>Medium</th><th>Pageviews</th><th>Visits</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(function(row) {
                html += '<tr>';
                html += '<td>' + escapeHtml(row.utm_campaign || '-') + '</td>';
                html += '<td>' + escapeHtml(row.utm_source || '-') + '</td>';
                html += '<td>' + escapeHtml(row.utm_medium || '-') + '</td>';
                html += '<td>' + formatNumber(row.pageviews) + '</td>';
                html += '<td>' + formatNumber(row.visits) + '</td>';
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
        } else {
            var siteUrl = (leanAnalyticsAdmin && leanAnalyticsAdmin.siteUrl) ? leanAnalyticsAdmin.siteUrl : 'yoursite.com';
            html += '<div class="lean-empty-state">';
            html += '<div class="lean-empty-state-icon"></div>';
            html += '<p><strong>No campaign data yet</strong></p>';
            html += '<div class="lean-info-box" style="max-width: 500px; margin: 20px auto; text-align: left; background: var(--gray-50, #f8fafc); border: 1px solid var(--gray-200, #e2e8f0); border-radius: 8px; padding: 16px;">';
            html += '<p style="margin: 0 0 12px 0; color: var(--gray-600, #475569);"><strong>How to track campaigns:</strong></p>';
            html += '<p style="margin: 0 0 8px 0; color: var(--gray-600, #475569); font-size: 13px;">Add UTM parameters to your links:</p>';
            html += '<code style="display: block; background: var(--gray-200, #e2e8f0); padding: 10px 12px; border-radius: 6px; font-size: 12px; color: var(--gray-700, #334155); word-break: break-all;">' + escapeHtml(siteUrl) + '/?utm_source=twitter&utm_medium=social&utm_campaign=summer_sale</code>';
            html += '<p style="margin: 12px 0 0 0; font-size: 12px; color: var(--gray-500, #64748b);">Switchboard automatically tracks utm_source, utm_medium, and utm_campaign parameters.</p>';
            html += '</div>';
            html += '</div>';
        }

        html += '</div>';
        return html;
    }

    // Full Entry Pages Tab
    function renderFullEntryPages() {
        var data = allData.entry_pages;
        var html = '<div class="lean-full-table-container">';
        
        html += '<h2>Entry Pages</h2>';
        
        if (data && data.length > 0) {
            html += '<table class="lean-full-table">';
            html += '<thead><tr><th>Page</th><th>Entries</th><th>New Visitors</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(function(row) {
                var displayPath = formatPath(row.path);
                html += '<tr>';
                html += '<td><a href="' + escapeHtml(row.path) + '" class="lean-table-link" target="_blank">' + escapeHtml(displayPath) + '</a></td>';
                html += '<td>' + formatNumber(row.entries) + '</td>';
                html += '<td>' + formatNumber(row.new_visitors) + '</td>';
                html += '</tr>';
            });

            html += '</tbody>';
            html += '</table>';
        } else {
            html += renderEmptyStateWithInfo('🚪', 'No entry page data yet', 'Entry pages show where visitors first land on your site. This helps identify which pages attract new visitors from search engines or external links.');
        }

        html += '</div>';
        return html;
    }

    // Full Exit Pages Tab
    function renderFullExitPages() {
        var data = allData.exit_pages;
        var html = '<div class="lean-full-table-container">';

        html += '<h2>Exit Pages</h2>';

        if (data && data.length > 0) {
            html += '<table class="lean-full-table">';
            html += '<thead><tr><th>Page</th><th>Exits</th></tr></thead>';
            html += '<tbody>';

            data.forEach(function(row) {
                var displayPath = formatPath(row.path);
                html += '<tr>';
                html += '<td><a href="' + escapeHtml(row.path) + '" class="lean-table-link" target="_blank">' + escapeHtml(displayPath) + '</a></td>';
                html += '<td>' + formatNumber(row.exits) + '</td>';
                html += '</tr>';
            });

            html += '</tbody>';
            html += '</table>';
        } else {
            html += renderEmptyStateWithInfo('🚪', 'No exit page data yet', 'Exit pages show the last page visitors view before leaving your site. High exit rates on certain pages may indicate areas for improvement.');
        }

        html += '</div>';
        return html;
    }

    // Real-Time Functionality
    var realtimeInterval = null;

    function loadRealTimeMetric() {
        return $.ajax({
            url: leanAnalyticsAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'lean_analytics_realtime',
                nonce: leanAnalyticsAdmin.nonce
            }
        }).fail(function(xhr, status, error) {
            console.error('Failed to load realtime metric:', status, error, xhr.responseText);
        });
    }

    function startRealtimeRefresh() {
        // Clear any existing interval
        if (realtimeInterval) {
            clearInterval(realtimeInterval);
        }

        // Auto-refresh every 10 seconds when on overview tab
        realtimeInterval = setInterval(function() {
            if (currentTab === 'overview') {
                updateRealtimeData();
            } else {
                clearInterval(realtimeInterval);
            }
        }, 10000); // 10 seconds
    }

    function updateRealtimeData() {
        loadRealTimeMetric().done(function(response) {
            if (response.success && currentTab === 'overview') {
                allData.realtime = response.data;
                // Update just the real-time stat card
                var realtimeCount = response.data.active_visitors || 0;
                $('#realtime-stat-value').text(formatNumber(realtimeCount));
                // Update active pages card
                updateActivePagesCard(response.data);
            }
        });
    }

    function renderRealtimeStatCard(label, value, icon) {
        var html = '<div class="lean-stat-card lean-stat-card-realtime" id="realtime-stat-card">';
        html += '<div class="lean-stat-label">' + icon + ' ' + label + ' <span class="lean-pulse-dot"></span></div>';
        html += '<div class="lean-stat-value" id="realtime-stat-value">' + value + '</div>';
        html += '</div>';
        return html;
    }

    function renderActivePagesCard(title, realtimeData) {
        var html = '<div class="lean-data-card">';
        html += '<div class="lean-data-card-header">';
        html += '<h3>' + title + '</h3>';
        html += '<span class="lean-live-badge">';
        html += '<span class="lean-pulse-dot" style="width: 6px; height: 6px; background: white; animation: none;"></span>';
        html += 'LIVE</span>';
        html += '</div>';
        html += '<div class="lean-data-card-body" id="active-pages-body">';

        if (realtimeData && realtimeData.active_pages && realtimeData.active_pages.length > 0) {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Path</th>';
            html += '<th class="lean-mini-number">Visitors</th>';
            html += '<th class="lean-mini-number">Time</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            var pages = realtimeData.active_pages.slice(0, 10);
            pages.forEach(function(page) {
                var timeAgo = formatTimeAgo(page.seconds_ago);
                var displayPath = formatPath(page.path);
                html += '<tr>';
                html += '<td><a href="' + escapeHtml(page.path) + '" class="lean-table-link" target="_blank">' + escapeHtml(displayPath) + '</a></td>';
                html += '<td class="lean-mini-number">' + formatNumber(page.visitors) + '</td>';
                html += '<td class="lean-mini-number" style="color: var(--lean-primary);">' + timeAgo + '</td>';
                html += '</tr>';
            });

            html += '</tbody>';
            html += '</table>';
        } else {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No active visitors</p></div>';
        }

        html += '</div></div>';
        return html;
    }

    function updateActivePagesCard(realtimeData) {
        var html = '';
        if (realtimeData && realtimeData.active_pages && realtimeData.active_pages.length > 0) {
            html += '<table class="lean-mini-table">';
            html += '<thead><tr>';
            html += '<th>Path</th>';
            html += '<th class="lean-mini-number">Visitors</th>';
            html += '<th class="lean-mini-number">Time</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            var pages = realtimeData.active_pages.slice(0, 10);
            pages.forEach(function(page) {
                var timeAgo = formatTimeAgo(page.seconds_ago);
                var displayPath = formatPath(page.path);
                html += '<tr>';
                html += '<td><a href="' + escapeHtml(page.path) + '" class="lean-table-link" target="_blank">' + escapeHtml(displayPath) + '</a></td>';
                html += '<td class="lean-mini-number">' + formatNumber(page.visitors) + '</td>';
                html += '<td class="lean-mini-number" style="color: var(--lean-primary);">' + timeAgo + '</td>';
                html += '</tr>';
            });

            html += '</tbody>';
            html += '</table>';
        } else {
            html += '<div class="lean-empty-state" style="padding: 30px;"><p>No active visitors</p></div>';
        }
        $('#active-pages-body').html(html);
    }

    function formatTimeAgo(seconds) {
        if (seconds < 10) return 'just now';
        if (seconds < 60) return seconds + 's ago';
        var minutes = Math.floor(seconds / 60);
        if (minutes === 1) return '1 min ago';
        if (minutes < 60) return minutes + ' mins ago';
        return 'over 1 hour ago';
    }
    
})(jQuery);