<div class="tab-pane fade" id="behavioralAnalysis" role="tabpanel">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h5 class="card-title">تحلیل رفتاری کاربران</h5>
        <div class="btn-group">
            <button type="button" class="btn btn-sm btn-outline-primary active" data-behavioral-chart="engagement">میزان تعامل</button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-behavioral-chart="sessions">جلسات کاربری</button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-behavioral-chart="retention">نرخ بازگشت</button>
        </div>
    </div>

    <!-- Filters Row -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <h6 class="card-subtitle mb-0">فیلترها</h6>
                        <div class="d-flex">
                            <div class="form-group ml-3 mb-0">
                                <label for="timeRange" class="mr-2">بازه زمانی:</label>
                                <select class="form-control form-control-sm" id="timeRange">
                                    <option value="7">7 روز گذشته</option>
                                    <option value="30" selected>30 روز گذشته</option>
                                    <option value="90">90 روز گذشته</option>
                                    <option value="180">6 ماه گذشته</option>
                                    <option value="365">1 سال گذشته</option>
                                </select>
                            </div>
                            <div class="form-group ml-3 mb-0">
                                <label for="userSegment" class="mr-2">نوع کاربر:</label>
                                <select class="form-control form-control-sm" id="userSegment">
                                    <option value="all" selected>تمام کاربران</option>
                                    <option value="new">کاربران جدید</option>
                                    <option value="returning">کاربران بازگشتی</option>
                                    <option value="active">کاربران فعال</option>
                                    <option value="inactive">کاربران غیرفعال</option>
                                </select>
                            </div>
                            <div class="form-group ml-3 mb-0">
                                <label for="deviceType" class="mr-2">نوع دستگاه:</label>
                                <select class="form-control form-control-sm" id="deviceType">
                                    <option value="all" selected>تمام دستگاه‌ها</option>
                                    <option value="desktop">دسکتاپ</option>
                                    <option value="mobile">موبایل</option>
                                    <option value="tablet">تبلت</option>
                                </select>
                            </div>
                            <button id="applyBehavioralFilters" class="btn btn-primary btn-sm">اعمال فیلترها</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- Engagement Metrics -->
        <div class="col-md-8 mb-4 behavioral-chart" id="engagement-chart-container" data-chart-type="engagement">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">روند تعامل کاربران</h6>
                    <div id="engagement-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-4 behavioral-chart" id="engagement-stats-container" data-chart-type="engagement">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">آمار تعامل</h6>
                    <div id="engagement-stats" class="stats-list">
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>میانگین زمان بازدید:</span>
                                <strong>4 دقیقه و 23 ثانیه</strong>
                            </div>
                        </div>
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>میانگین صفحات بازدید شده:</span>
                                <strong>3.7 صفحه / جلسه</strong>
                            </div>
                        </div>
                        <div class="alert alert-success mb-2">
                            <div class="d-flex justify-content-between">
                                <span>نرخ تعامل:</span>
                                <strong>46.8% (+5.3%)</strong>
                            </div>
                        </div>
                        <div class="alert alert-warning mb-2">
                            <div class="d-flex justify-content-between">
                                <span>نرخ خروج:</span>
                                <strong>32.6% (-2.1%)</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sessions Metrics -->
        <div class="col-md-8 mb-4 behavioral-chart d-none" id="sessions-chart-container" data-chart-type="sessions">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">روند جلسات کاربری</h6>
                    <div id="sessions-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-4 behavioral-chart d-none" id="sessions-stats-container" data-chart-type="sessions">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">آمار جلسات</h6>
                    <div id="sessions-stats" class="stats-list">
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>کل جلسات:</span>
                                <strong>87,423</strong>
                            </div>
                        </div>
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>جلسات کاربران جدید:</span>
                                <strong>23,156 (26.5%)</strong>
                            </div>
                        </div>
                        <div class="alert alert-success mb-2">
                            <div class="d-flex justify-content-between">
                                <span>رشد جلسات:</span>
                                <strong>+12.8% نسبت به دوره قبل</strong>
                            </div>
                        </div>
                        <div class="alert alert-warning mb-2">
                            <div class="d-flex justify-content-between">
                                <span>نرخ پرش:</span>
                                <strong>42.3% (-1.5%)</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Retention Metrics -->
        <div class="col-md-8 mb-4 behavioral-chart d-none" id="retention-chart-container" data-chart-type="retention">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">نمودار نرخ بازگشت کاربران</h6>
                    <div id="retention-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-4 behavioral-chart d-none" id="retention-stats-container" data-chart-type="retention">
            <div class="card h-100">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">آمار بازگشت</h6>
                    <div id="retention-stats" class="stats-list">
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>نرخ بازگشت 7 روزه:</span>
                                <strong>34.2%</strong>
                            </div>
                        </div>
                        <div class="alert alert-info mb-2">
                            <div class="d-flex justify-content-between">
                                <span>نرخ بازگشت 30 روزه:</span>
                                <strong>23.8%</strong>
                            </div>
                        </div>
                        <div class="alert alert-success mb-2">
                            <div class="d-flex justify-content-between">
                                <span>بهبود نرخ بازگشت:</span>
                                <strong>+4.2% نسبت به دوره قبل</strong>
                            </div>
                        </div>
                        <div class="alert alert-warning mb-2">
                            <div class="d-flex justify-content-between">
                                <span>کاربران از دست رفته:</span>
                                <strong>3,241 در 30 روز گذشته</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- User Flow Visualization -->
    <div class="row">
        <div class="col-md-12 mb-4">
            <div class="card">
                <div class="card-body">
                    <h6 class="card-subtitle mb-3">مسیر کاربران در سایت</h6>
                    <div id="user-flow-diagram" class="user-flow-container">
                        <div class="flow-chart-placeholder">
                            <div class="flow-nodes">
                                <div class="flow-node start-node">
                                    <div class="node-content">
                                        <span class="node-title">صفحه اصلی</span>
                                        <span class="node-stat">100%</span>
                                    </div>
                                </div>
                                
                                <div class="flow-level">
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">جستجو</span>
                                            <span class="node-stat">32%</span>
                                        </div>
                                    </div>
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">دسته‌بندی</span>
                                            <span class="node-stat">28%</span>
                                        </div>
                                    </div>
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">مقالات</span>
                                            <span class="node-stat">18%</span>
                                        </div>
                                    </div>
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">خروج</span>
                                            <span class="node-stat">22%</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="flow-level">
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">صفحه محصول</span>
                                            <span class="node-stat">45%</span>
                                        </div>
                                    </div>
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">سبد خرید</span>
                                            <span class="node-stat">15%</span>
                                        </div>
                                    </div>
                                    <div class="flow-node">
                                        <div class="node-content">
                                            <span class="node-title">خروج</span>
                                            <span class="node-stat">40%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="alert alert-primary">
                                <strong><i class="fas fa-info-circle"></i> تحلیل مسیر کاربران</strong>
                                <p class="mt-2 mb-0">
                                    مسیر اصلی کاربران از صفحه اصلی به جستجو و سپس صفحه محصول است. نرخ خروج بالا از صفحه محصول (40%) نشان می‌دهد که این نقطه نیاز به بهینه‌سازی دارد. پیشنهاد می‌شود محتوای صفحات محصول و عناصر ترغیب کننده به خرید بهبود یابند.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle between different behavioral chart types
    document.querySelectorAll('[data-behavioral-chart]').forEach(button => {
        button.addEventListener('click', function() {
            // Remove active class from all buttons
            document.querySelectorAll('[data-behavioral-chart]').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // Add active class to clicked button
            this.classList.add('active');
            
            // Hide all chart containers
            document.querySelectorAll('.behavioral-chart').forEach(container => {
                container.classList.add('d-none');
            });
            
            // Show the selected chart containers
            const chartType = this.getAttribute('data-behavioral-chart');
            document.querySelectorAll(`[data-chart-type="${chartType}"]`).forEach(container => {
                container.classList.remove('d-none');
            });
            
            // Initialize or refresh the visible charts
            initBehavioralCharts(chartType);
        });
    });
    
    // Apply filters button event
    document.getElementById('applyBehavioralFilters').addEventListener('click', function() {
        const timeRange = document.getElementById('timeRange').value;
        const userSegment = document.getElementById('userSegment').value;
        const deviceType = document.getElementById('deviceType').value;
        
        // Get active chart type
        const activeChartType = document.querySelector('[data-behavioral-chart].active').getAttribute('data-behavioral-chart');
        
        // Apply filters by refreshing charts
        initBehavioralCharts(activeChartType, { timeRange, userSegment, deviceType });
    });
    
    // Initialize the default engagement charts on page load
    initBehavioralCharts('engagement');
});

function initBehavioralCharts(chartType, filters = {}) {
    // Show loading indicators if needed
    // ...
    
    // In a real application, this would make an AJAX request to fetch data with filters
    // For now, we'll just simulate with sample data
    
    if (chartType === 'engagement') {
        renderEngagementChart(filters);
    } else if (chartType === 'sessions') {
        renderSessionsChart(filters);
    } else if (chartType === 'retention') {
        renderRetentionChart(filters);
    }
}

function renderEngagementChart(filters = {}) {
    // Sample data for engagement - in a real app, this would come from the server with filters applied
    const dates = ['01/10', '02/10', '03/10', '04/10', '05/10', '06/10', '07/10', '08/10', '09/10', '10/10',
                   '11/10', '12/10', '13/10', '14/10', '15/10', '16/10', '17/10', '18/10', '19/10', '20/10',
                   '21/10', '22/10', '23/10', '24/10', '25/10', '26/10', '27/10', '28/10', '29/10', '30/10'];
    
    const pageViewsPerSession = [2.8, 3.1, 2.9, 3.2, 3.5, 3.7, 3.4, 3.2, 3.6, 3.9,
                               4.1, 3.8, 3.5, 3.7, 3.9, 4.0, 3.8, 3.6, 3.5, 3.7,
                               3.8, 3.9, 4.2, 4.0, 3.8, 3.7, 3.6, 3.8, 4.1, 3.7];
    
    const avgSessionDuration = [3.1, 3.4, 3.2, 3.5, 3.8, 4.0, 3.7, 3.5, 3.9, 4.2,
                               4.4, 4.1, 3.8, 4.0, 4.2, 4.3, 4.1, 3.9, 3.8, 4.0,
                               4.1, 4.2, 4.5, 4.3, 4.1, 4.0, 3.9, 4.1, 4.4, 4.0];
    
    const options = {
        series: [{
            name: 'صفحات بازدید شده در هر جلسه',
            data: pageViewsPerSession
        }, {
            name: 'مدت زمان متوسط جلسه (دقیقه)',
            data: avgSessionDuration
        }],
        chart: {
            height: 350,
            type: 'line',
            fontFamily: 'Vazir, sans-serif',
            dir: 'rtl',
            toolbar: {
                show: true
            }
        },
        colors: ['#3A5794', '#FF9800'],
        dataLabels: {
            enabled: false
        },
        stroke: {
            width: [3, 3],
            curve: 'smooth'
        },
        xaxis: {
            categories: dates,
            labels: {
                rotate: -45
            }
        },
        yaxis: [{
            title: {
                text: 'صفحات در هر جلسه'
            }
        }, {
            opposite: true,
            title: {
                text: 'مدت جلسه (دقیقه)'
            }
        }],
        tooltip: {
            shared: true,
            intersect: false
        },
        legend: {
            position: 'top'
        }
    };

    const chart = new ApexCharts(document.querySelector("#engagement-chart"), options);
    chart.render();
}

function renderSessionsChart(filters = {}) {
    // Sample data for sessions
    const dates = ['01/10', '02/10', '03/10', '04/10', '05/10', '06/10', '07/10', '08/10', '09/10', '10/10',
                   '11/10', '12/10', '13/10', '14/10', '15/10', '16/10', '17/10', '18/10', '19/10', '20/10',
                   '21/10', '22/10', '23/10', '24/10', '25/10', '26/10', '27/10', '28/10', '29/10', '30/10'];
    
    const totalSessions = [1250, 1380, 1320, 1450, 1520, 1680, 1790, 1650, 1480, 1520,
                         1610, 1750, 1830, 1920, 2050, 1980, 1870, 1750, 1690, 1820,
                         1940, 2080, 2150, 2080, 1950, 1870, 1950, 2050, 2170, 2090];
    
    const newUserSessions = [320, 350, 330, 380, 410, 450, 490, 440, 390, 410,
                            430, 470, 500, 520, 560, 540, 510, 480, 460, 500,
                            530, 570, 590, 570, 530, 510, 530, 560, 590, 570];
    
    const options = {
        series: [{
            name: 'کل جلسات',
            data: totalSessions
        }, {
            name: 'جلسات کاربران جدید',
            data: newUserSessions
        }],
        chart: {
            type: 'area',
            height: 350,
            fontFamily: 'Vazir, sans-serif',
            dir: 'rtl',
            stacked: false,
            toolbar: {
                show: true
            }
        },
        colors: ['#4CAF50', '#2196F3'],
        dataLabels: {
            enabled: false
        },
        stroke: {
            curve: 'smooth',
            width: [3, 3]
        },
        fill: {
            type: 'gradient',
            gradient: {
                opacityFrom: 0.6,
                opacityTo: 0.1
            }
        },
        xaxis: {
            categories: dates,
            labels: {
                rotate: -45
            }
        },
        yaxis: {
            title: {
                text: 'تعداد جلسات'
            }
        },
        tooltip: {
            shared: true,
            intersect: false
        },
        legend: {
            position: 'top'
        }
    };

    const chart = new ApexCharts(document.querySelector("#sessions-chart"), options);
    chart.render();
}

function renderRetentionChart(filters = {}) {
    // Sample data for retention cohort
    const options = {
        series: [
            {
                name: 'هفته 1',
                data: [100, 34, 28, 23, 19, 16, 14, 12, 10, 9, 8, 7]
            },
            {
                name: 'هفته 2',
                data: [100, 36, 30, 25, 21, 18, 16, 14, 12, 11, 10]
            },
            {
                name: 'هفته 3',
                data: [100, 38, 32, 27, 23, 20, 18, 16, 14, 13]
            },
            {
                name: 'هفته 4',
                data: [100, 40, 34, 29, 25, 22, 20, 18, 16]
            },
            {
                name: 'هفته 5',
                data: [100, 42, 36, 31, 27, 24, 22, 20]
            }
        ],
        chart: {
            type: 'line',
            height: 350,
            fontFamily: 'Vazir, sans-serif',
            dir: 'rtl',
            toolbar: {
                show: true
            }
        },
        dataLabels: {
            enabled: true,
            enabledOnSeries: undefined,
            formatter: function (val) {
                return val + '%';
            },
            style: {
                fontSize: '10px',
                colors: ['#304758']
            }
        },
        stroke: {
            width: 3,
            curve: 'smooth'
        },
        xaxis: {
            categories: ['روز 1', 'روز 7', 'روز 14', 'روز 21', 'روز 28', 'روز 35', 'روز 42', 'روز 49', 'روز 56', 'روز 63', 'روز 70', 'روز 77'],
            labels: {
                rotate: -45
            },
            title: {
                text: 'روزها پس از ثبت‌نام'
            }
        },
        yaxis: {
            title: {
                text: 'نرخ بازگشت (%)'
            },
            min: 0,
            max: 100
        },
        colors: ['#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5'],
        tooltip: {
            shared: false,
            y: {
                formatter: function (val) {
                    return val + '%';
                }
            }
        },
        legend: {
            position: 'top'
        }
    };

    const chart = new ApexCharts(document.querySelector("#retention-chart"), options);
    chart.render();
}

// Add custom style for user flow diagram
document.head.insertAdjacentHTML('beforeend', `
<style>
.user-flow-container {
    overflow-x: auto;
}
.flow-chart-placeholder {
    min-height: 250px;
    padding: 20px 0;
}
.flow-nodes {
    display: flex;
    flex-direction: column;
    align-items: center;
}
.flow-level {
    display: flex;
    justify-content: center;
    width: 100%;
    margin: 20px 0;
    position: relative;
}
.flow-level:before {
    content: '';
    position: absolute;
    top: -20px;
    left: 0;
    width: 100%;
    height: 1px;
    background: #e0e0e0;
}
.flow-node {
    background: #f5f5f5;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px 15px;
    margin: 0 15px;
    min-width: 120px;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    position: relative;
}
.flow-node:after {
    content: '';
    position: absolute;
    top: -10px;
    left: 50%;
    transform: translateX(-50%);
    width: 1px;
    height: 10px;
    background: #e0e0e0;
}
.flow-node .node-title {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
}
.flow-node .node-stat {
    display: block;
    color: #666;
    font-size: 0.85rem;
}
.start-node {
    background: #e1f5fe;
    border-color: #81d4fa;
}
</style>
`);
</script> 