

<?php $__env->startSection('title', 'پنل تحلیل داده‌ها'); ?>

<?php $__env->startSection('styles'); ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts/dist/apexcharts.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
    <style>
        .card-analytics {
            border-radius: 0.75rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1.5rem;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .card-analytics:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }

        .chart-container {
            position: relative;
            height: 350px;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
        }

        .stat-label {
            font-size: 0.875rem;
            color: #6c757d;
        }

        .trend-indicator {
            font-size: 0.875rem;
            padding: 0.25rem 0.5rem;
            border-radius: 1rem;
        }

        .trend-indicator.positive {
            background-color: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }

        .trend-indicator.negative {
            background-color: rgba(220, 53, 69, 0.15);
            color: #dc3545;
        }

        .tab-pane {
            padding: 1.5rem 0;
        }

        .time-filter {
            display: inline-block;
            margin-left: 1rem;
        }

        .map-container {
            height: 500px;
            width: 100%;
        }

        /* اصلاح استایل تب‌ها برای خوانایی بهتر */
        .nav-tabs .nav-link {
            color: #495057;
            font-weight: 500;
        }

        .nav-tabs .nav-link:hover {
            color: #2e59d9;
        }

        .nav-tabs .nav-link.active {
            color: #2e59d9;
            font-weight: 600;
        }

        /* استایل نقشه حرارتی ایران */
        #iran-heatmap {
            height: 500px;
            width: 100%;
            background-color: #f8f9fc;
        }

        /* Enhanced Trends Analysis Styles */
        .trends-header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .trends-main-title {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: white;
        }

        .trends-subtitle {
            font-size: 1rem;
            opacity: 0.9;
            color: white !important;
        }

        .trends-toggle-group .btn {
            border-radius: 25px;
            padding: 0.5rem 1.25rem;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid #667eea;
        }

        .trends-toggle-group .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .trends-toggle-group .btn.active {
            background: #667eea;
            border-color: #667eea;
            color: white;
        }

        /* Enhanced Chart Cards */
        .trends-chart-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .trends-chart-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .trends-chart-card .card-header {
            border: none;
            padding: 1.5rem;
        }

        .chart-actions .btn {
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            margin-left: 0.5rem;
            transition: all 0.3s ease;
        }

        .chart-actions .btn:hover {
            transform: scale(1.1);
        }

        /* Enhanced Statistics Table */
        .trends-stats-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .trends-stats-table {
            font-size: 0.9rem;
        }

        .trends-stats-row:hover {
            background-color: rgba(102, 126, 234, 0.05);
        }

        .trend-indicator-enhanced {
            padding: 0.4rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
        }

        .trend-indicator-enhanced.positive {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .trend-indicator-enhanced.negative {
            background: linear-gradient(135deg, #dc3545, #fd7e14);
            color: white;
        }

        .trends-summary {
            border-top: 1px solid #e9ecef;
        }

        .summary-item {
            padding: 0.5rem;
        }

        .summary-value {
            font-size: 1.25rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .summary-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Enhanced Categories Section */
        .trends-categories-section {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .trends-category-card {
            border-radius: 12px;
            transition: all 0.3s ease;
            border-width: 2px;
        }

        .trends-category-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
        }

        .category-info .card-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .category-rank .badge {
            font-size: 0.75rem;
            padding: 0.4rem 0.8rem;
            border-radius: 15px;
        }

        .trend-indicator-large {
            padding: 0.6rem 1rem;
            border-radius: 25px;
            font-size: 1rem;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 0.4rem;
        }

        .trend-indicator-large.positive {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }

        .trend-indicator-large.negative {
            background: linear-gradient(135deg, #dc3545, #fd7e14);
            color: white;
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
        }

        .category-stats .stat-item {
            padding: 0.75rem;
            border-radius: 8px;
            background: rgba(102, 126, 234, 0.05);
        }

        .category-stats .stat-value {
            font-size: 1.25rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .category-stats .stat-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        .category-progress .progress-label {
            font-size: 0.85rem;
            font-weight: 500;
            color: #495057;
        }

        .category-progress .progress-value {
            font-size: 0.85rem;
            font-weight: 600;
            color: #667eea;
        }

        .change-indicator {
            padding: 0.5rem;
            border-radius: 8px;
            background: rgba(248, 249, 250, 0.8);
        }

        /* Enhanced Forecast Section */
        .trends-forecast-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .forecast-item {
            padding: 1rem;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
        }

        .forecast-item:hover {
            background: rgba(102, 126, 234, 0.05);
            transform: translateY(-2px);
        }

        .forecast-period i {
            font-size: 1.5rem;
        }

        .forecast-value .display-5 {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
        }

        .forecast-confidence {
            margin-top: 0.5rem;
        }

        .forecast-details {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border: 1px solid #dee2e6;
        }

        .detail-item {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .detail-label {
            font-weight: 500;
            margin-right: 0.5rem;
            color: #495057;
        }

        .detail-value {
            font-weight: 600;
            color: #667eea;
        }

        /* Enhanced Recommendations Section */
        .trends-recommendations-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .recommendation-item {
            border-radius: 12px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
        }

        .recommendation-item:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .recommendation-icon {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.9);
        }

        .recommendation-title {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .recommendation-text {
            font-size: 0.9rem;
            line-height: 1.5;
            color: #495057;
        }

        .recommendations-actions {
            background: rgba(248, 249, 250, 0.5);
        }

        /* Enhanced Category Analysis Styles */
        .category-header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .category-main-title {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: white;
        }

        .category-subtitle {
            font-size: 1rem;
            opacity: 0.9;
            color: white !important;
        }

        .category-toggle-group .btn {
            border-radius: 25px;
            padding: 0.5rem 1.25rem;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid #667eea;
        }

        .category-toggle-group .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .category-toggle-group .btn.active {
            background: #667eea;
            border-color: #667eea;
            color: white;
        }

        /* Quick Stats Cards */
        .category-stats-overview {
            margin-bottom: 2rem;
        }

        .stat-card {
            background: linear-gradient(135deg, #fff, #f8f9fc);
            border-radius: 15px;
            padding: 1.5rem;
            border: none;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }

        .stat-content {
            flex: 1;
        }

        .stat-value {
            font-size: 1.75rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Enhanced Chart Cards */
        .category-chart-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .category-chart-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .category-chart-card .card-header {
            border: none;
            padding: 1.5rem;
        }

        .category-stats-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        /* Category Statistics List */
        .category-stats-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .category-stat-item {
            border-bottom: 1px solid #f1f3fa;
            transition: all 0.3s ease;
        }

        .category-stat-item:hover {
            background-color: rgba(102, 126, 234, 0.05);
        }

        .category-color-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 0.75rem;
            flex-shrink: 0;
        }

        .category-info .category-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .category-info .category-rank {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .category-metrics .category-count {
            font-weight: 700;
            color: #667eea;
            font-size: 1.1rem;
        }

        .category-metrics .category-percentage {
            font-size: 0.9rem;
            color: #6c757d;
        }

        .category-progress-bar {
            padding: 0 1rem 0.5rem;
        }

        .category-stats-summary {
            border-top: 1px solid #e9ecef;
        }

        .summary-metric {
            padding: 0.5rem;
        }

        .metric-value {
            font-size: 1.25rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .metric-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Enhanced Category Status Cards */
        .category-status-section {
            margin-top: 2rem;
        }

        .category-status-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .category-status-item {
            background: linear-gradient(135deg, #fff, #f8f9fc);
            border-radius: 15px;
            padding: 1.5rem;
            border: 2px solid transparent;
            transition: all 0.3s ease;
            height: 100%;
        }

        .category-status-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
        }

        .category-status-item.growing {
            border-color: rgba(40, 167, 69, 0.3);
        }

        .category-status-item.declining {
            border-color: rgba(220, 53, 69, 0.3);
        }

        .category-title-section {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .category-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
        }

        .category-details .category-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .category-badge .badge {
            font-size: 0.75rem;
            padding: 0.4rem 0.8rem;
            border-radius: 15px;
        }

        .growth-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
        }

        .growth-badge.positive {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }

        .growth-badge.negative {
            background: linear-gradient(135deg, #dc3545, #fd7e14);
            color: white;
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
        }

        .category-metrics {
            margin: 1rem 0;
        }

        .metric-item {
            text-align: center;
            padding: 0.75rem;
            border-radius: 8px;
            background: rgba(102, 126, 234, 0.05);
        }

        .metric-item .metric-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 0.25rem;
        }

        .metric-item .metric-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        .category-progress-section {
            margin: 1rem 0;
        }

        .progress-label {
            font-size: 0.85rem;
            font-weight: 500;
            color: #495057;
        }

        .progress-percentage {
            font-size: 0.85rem;
            font-weight: 600;
            color: #667eea;
        }

        .category-progress {
            border-radius: 10px;
            overflow: hidden;
        }

        .category-insights {
            margin-top: 1rem;
        }

        .insight-item {
            padding: 0.5rem 0.75rem;
            border-radius: 8px;
            font-size: 0.85rem;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
        }

        .insight-item.success {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
        }

        .insight-item.info {
            background: rgba(23, 162, 184, 0.1);
            color: #17a2b8;
        }

        .insight-item.warning {
            background: rgba(255, 193, 7, 0.1);
            color: #ffc107;
        }

        .insight-item.danger {
            background: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .trends-header-section,
            .category-header-section {
                padding: 1.5rem;
                text-align: center;
            }

            .trends-main-title,
            .category-main-title {
                font-size: 1.5rem;
            }

            .trends-controls,
            .category-controls {
                justify-content: center !important;
                margin-top: 1rem;
            }

            .trends-toggle-group,
            .category-toggle-group {
                flex-direction: column;
                width: 100%;
            }

            .trends-toggle-group .btn,
            .category-toggle-group .btn {
                margin-bottom: 0.5rem;
                border-radius: 8px;
            }

            .forecast-value .display-5 {
                font-size: 1.5rem;
            }

            .recommendation-item {
                margin-bottom: 1rem;
            }

            .stat-card {
                flex-direction: column;
                text-align: center;
                gap: 0.5rem;
            }

            .category-title-section {
                flex-direction: column;
                text-align: center;
                gap: 0.5rem;
            }

            .category-status-item {
                margin-bottom: 1rem;
            }
        }

        /* Enhanced Rating Analysis Styles */
        .rating-header-section {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            border-radius: 15px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(255, 193, 7, 0.3);
        }

        .rating-main-title {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: white;
        }

        .rating-subtitle {
            font-size: 1rem;
            opacity: 0.9;
            color: white !important;
        }

        .rating-toggle-group .btn {
            border-radius: 25px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid #ffc107;
            margin-right: 0.25rem;
        }

        .rating-toggle-group .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 193, 7, 0.4);
        }

        .rating-toggle-group .btn.active {
            background: #ffc107;
            border-color: #ffc107;
            color: white;
        }

        /* Rating Overview Cards */
        .rating-overview-section {
            margin-bottom: 2rem;
        }

        .rating-overview-card {
            background: linear-gradient(135deg, #fff, #f8f9fc);
            border-radius: 15px;
            padding: 1.5rem;
            border: none;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 1rem;
            height: 100%;
        }

        .rating-overview-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }

        .rating-overview-card .card-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            flex-shrink: 0;
        }

        .rating-overview-card .card-content {
            flex: 1;
        }

        .rating-overview-card .card-value {
            font-size: 1.75rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .rating-overview-card .card-label {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }

        .rating-overview-card .card-trend {
            font-size: 0.8rem;
            font-weight: 600;
        }

        .rating-overview-card .card-trend.positive {
            color: #28a745;
        }

        .rating-overview-card .card-detail {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .rating-stars-small {
            font-size: 0.9rem;
        }

        /* Enhanced Chart Cards */
        .rating-chart-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .rating-chart-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .rating-chart-card .card-header {
            border: none;
            padding: 1.5rem;
        }

        .chart-actions .btn {
            margin-left: 0.25rem;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        /* Rating Statistics Panel */
        .rating-stats-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .main-rating-display {
            position: relative;
        }

        .rating-circle {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #ffc107, #fd7e14);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1rem;
            position: relative;
            box-shadow: 0 10px 30px rgba(255, 193, 7, 0.3);
        }

        .rating-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: white;
            line-height: 1;
        }

        .rating-max {
            font-size: 1.2rem;
            color: rgba(255, 255, 255, 0.8);
            margin-left: 0.25rem;
        }

        .rating-description .rating-label {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .rating-description .rating-count {
            font-size: 0.9rem;
            color: #6c757d;
        }

        .rating-stars-display {
            font-size: 1.2rem;
            margin-top: 0.5rem;
        }

        /* Rating Breakdown */
        .breakdown-title {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .rating-breakdown-item {
            margin-bottom: 1rem;
        }

        .rating-star-label {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .star-number {
            font-weight: 600;
            color: #2c3e50;
            min-width: 20px;
        }

        .rating-stats {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .rating-count-badge {
            background: #f8f9fc;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .rating-percent {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        .rating-progress {
            border-radius: 10px;
            overflow: hidden;
        }

        /* Rating Insights */
        .insights-title {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .insights-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
        }

        .insight-item {
            text-align: center;
            padding: 1rem;
            border-radius: 10px;
            background: #f8f9fc;
        }

        .insight-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
            margin: 0 auto 0.5rem;
        }

        .insight-content .insight-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .insight-content .insight-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Sentiment Analysis */
        .sentiment-summary {
            padding: 1.5rem;
            background: #f8f9fc;
            border-radius: 15px;
        }

        .sentiment-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .sentiment-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            border-radius: 10px;
            background: white;
            margin-bottom: 1rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .sentiment-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
        }

        .sentiment-item.positive .sentiment-icon {
            background: linear-gradient(135deg, #28a745, #20c997);
        }

        .sentiment-item.neutral .sentiment-icon {
            background: linear-gradient(135deg, #ffc107, #fd7e14);
        }

        .sentiment-item.negative .sentiment-icon {
            background: linear-gradient(135deg, #dc3545, #fd7e14);
        }

        .sentiment-content {
            flex: 1;
        }

        .sentiment-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .sentiment-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 0.25rem;
        }

        .sentiment-count {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .insights-subtitle {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.75rem;
        }

        .insight-point {
            padding: 0.5rem 0.75rem;
            border-radius: 8px;
            font-size: 0.85rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
        }

        .insight-point.success {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
        }

        .insight-point.warning {
            background: rgba(255, 193, 7, 0.1);
            color: #ffc107;
        }

        .insight-point.info {
            background: rgba(23, 162, 184, 0.1);
            color: #17a2b8;
        }

        /* Top Rated Locations */
        .rating-top-locations-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .top-rated-actions .btn {
            margin-left: 0.25rem;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .top-rated-item {
            border-bottom: 1px solid #f1f3fa;
            transition: all 0.3s ease;
        }

        .top-rated-item:hover {
            background-color: rgba(255, 193, 7, 0.05);
        }

        .top-rated-item.top-three {
            background: linear-gradient(135deg, rgba(255, 193, 7, 0.1), rgba(253, 126, 20, 0.05));
        }

        .rank-badge {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
            font-weight: 700;
            flex-shrink: 0;
        }

        .rank-badge.gold {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #b8860b;
            box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
        }

        .rank-badge.silver {
            background: linear-gradient(135deg, #c0c0c0, #e5e5e5);
            color: #696969;
            box-shadow: 0 5px 15px rgba(192, 192, 192, 0.4);
        }

        .rank-badge.bronze {
            background: linear-gradient(135deg, #cd7f32, #daa520);
            color: #8b4513;
            box-shadow: 0 5px 15px rgba(205, 127, 50, 0.4);
        }

        .rank-badge.regular {
            background: linear-gradient(135deg, #6c757d, #adb5bd);
            color: white;
        }

        .location-info .location-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .category-badge {
            background: #667eea;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .rating-display {
            min-width: 120px;
        }

        .rating-value-large {
            font-size: 1.5rem;
            font-weight: 700;
            color: #ffc107;
            margin-bottom: 0.25rem;
        }

        .rating-stars-row {
            margin-bottom: 0.25rem;
        }

        .rating-count-small {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .rating-progress-section {
            width: 60px;
        }

        .vertical-progress {
            width: 8px;
            height: 60px;
            background: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
        }

        .vertical-progress .progress-bar {
            width: 100%;
            transition: height 0.6s ease;
        }

        .location-actions .btn-group-vertical .btn {
            margin-bottom: 0.25rem;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .additional-stats {
            background: rgba(255, 193, 7, 0.05);
            border-top: 1px solid rgba(255, 193, 7, 0.2);
        }

        .stat-mini {
            padding: 0.5rem;
        }

        .stat-mini-value {
            font-size: 1.1rem;
            font-weight: 700;
            color: #ffc107;
            margin-bottom: 0.25rem;
        }

        .stat-mini-label {
            font-size: 0.7rem;
            color: #6c757d;
            font-weight: 500;
        }

        .empty-state {
            padding: 3rem 1rem;
        }

        .top-rated-summary {
            background: #f8f9fc;
        }

        .summary-stat {
            padding: 0.5rem;
        }

        .summary-value {
            font-size: 1.25rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .summary-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Enhanced Time Analysis Styles */
        .time-header-section {
            background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
            border-radius: 15px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(23, 162, 184, 0.3);
        }

        .time-main-title {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: white;
        }

        .time-subtitle {
            font-size: 1rem;
            opacity: 0.9;
            color: white !important;
        }

        .time-toggle-group .btn {
            border-radius: 25px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid #17a2b8;
            margin-right: 0.25rem;
        }

        .time-toggle-group .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(23, 162, 184, 0.4);
        }

        .time-toggle-group .btn.active {
            background: #17a2b8;
            border-color: #17a2b8;
            color: white;
        }

        /* Time Overview Cards */
        .time-overview-section {
            margin-bottom: 2rem;
        }

        .time-overview-card {
            background: linear-gradient(135deg, #fff, #f8f9fc);
            border-radius: 15px;
            padding: 1.5rem;
            border: none;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 1rem;
            height: 100%;
        }

        .time-overview-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }

        .time-overview-card .card-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            flex-shrink: 0;
        }

        .time-overview-card .card-content {
            flex: 1;
        }

        .time-overview-card .card-value {
            font-size: 1.75rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .time-overview-card .card-label {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }

        .time-overview-card .card-trend {
            font-size: 0.8rem;
            font-weight: 600;
        }

        .time-overview-card .card-trend.positive {
            color: #28a745;
        }

        .time-overview-card .card-trend.negative {
            color: #dc3545;
        }

        .time-overview-card .card-detail {
            font-size: 0.8rem;
            color: #6c757d;
        }

        /* Enhanced Chart Cards */
        .time-chart-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .time-chart-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .time-chart-card .card-header {
            border: none;
            padding: 1.5rem;
        }

        .chart-actions .btn {
            margin-left: 0.25rem;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        /* Time Statistics Panel */
        .time-stats-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .peak-activity-display {
            position: relative;
        }

        .activity-circle {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #17a2b8, #20c997);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1rem;
            position: relative;
            box-shadow: 0 10px 30px rgba(23, 162, 184, 0.3);
        }

        .activity-value {
            font-size: 2rem;
            font-weight: 700;
            color: white;
            line-height: 1;
        }

        .activity-label {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.8);
        }

        .activity-description .activity-title {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .activity-description .activity-date {
            font-size: 0.9rem;
            color: #6c757d;
        }

        /* Daily Breakdown */
        .breakdown-title {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .daily-breakdown-item {
            margin-bottom: 1rem;
        }

        .day-label .day-name {
            font-weight: 600;
            font-size: 0.9rem;
        }

        .day-stats {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .day-count-badge {
            background: #f8f9fc;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .day-percent {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        .day-progress {
            border-radius: 10px;
            overflow: hidden;
        }

        /* Daily Insights */
        .insights-title {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .insights-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
        }

        .insight-item {
            text-align: center;
            padding: 1rem;
            border-radius: 10px;
            background: #f8f9fc;
        }

        .insight-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
            margin: 0 auto 0.5rem;
        }

        .insight-content .insight-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .insight-content .insight-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Real-time Analysis */
        .realtime-info {
            background: rgba(23, 162, 184, 0.05);
            border-radius: 10px;
            padding: 1rem;
        }

        .realtime-metric {
            padding: 0.5rem;
        }

        .metric-value {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
            transition: all 0.3s ease;
        }

        .metric-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        /* Time Statistics Summary */
        .time-stats-summary-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .stats-actions .btn {
            margin-left: 0.25rem;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .performance-metrics,
        .growth-predictions {
            padding: 1rem;
            background: #f8f9fc;
            border-radius: 10px;
        }

        .metrics-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 1rem;
        }

        .metrics-grid {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .metric-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .metric-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #17a2b8, #20c997);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
        }

        .metric-content {
            flex: 1;
        }

        .metric-label {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }

        .metric-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #17a2b8;
            margin-bottom: 0.25rem;
        }

        .metric-detail {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .predictions-grid {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .prediction-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .prediction-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 0.75rem;
        }

        .prediction-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
        }

        .prediction-info {
            flex: 1;
        }

        .prediction-label {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }

        .prediction-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #2c3e50;
        }

        .prediction-trend {
            font-size: 0.8rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .prediction-trend.positive {
            color: #28a745;
        }

        .prediction-trend.negative {
            color: #dc3545;
        }

        .prediction-progress .progress {
            height: 6px;
            border-radius: 10px;
        }

        .prediction-confidence {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .confidence-label {
            font-weight: 500;
        }

        .confidence-value {
            font-weight: 700;
            color: #17a2b8;
        }

        .seasonal-info {
            margin-top: 0.5rem;
        }

        .seasonal-detail {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .empty-stats {
            padding: 3rem 1rem;
        }

        /* Additional Insights */
        .additional-insights {
            border-top: 1px solid #e9ecef;
            padding-top: 1.5rem;
        }

        .insight-box {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            height: 100%;
        }

        .insight-header {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.75rem;
            font-weight: 600;
            color: #2c3e50;
        }

        /* Pulse Animation */
        .pulse {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                opacity: 1;
            }
            50% {
                opacity: 0.5;
            }
            100% {
                opacity: 1;
            }
        }

        /* Geography Analysis Styles */
        .geo-header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
        }

        .geo-main-title {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .geo-subtitle {
            font-size: 1rem;
            opacity: 0.9;
        }

        .geo-toggle-group .btn {
            border-radius: 25px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .geo-toggle-group .btn.active {
            background: white;
            color: #667eea;
            border-color: white;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .geo-overview-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            height: 100%;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .geo-overview-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }

        .geo-overview-card .card-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            flex-shrink: 0;
        }

        .geo-overview-card .card-content {
            flex: 1;
        }

        .geo-overview-card .card-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .geo-overview-card .card-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0.5rem;
        }

        .geo-overview-card .card-trend {
            font-size: 0.8rem;
            font-weight: 500;
        }

        .geo-overview-card .card-trend.positive {
            color: #28a745;
        }

        .geo-overview-card .card-detail {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .geo-chart-card, .geo-ranking-card, .geo-heatmap-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid #f0f0f0;
            overflow: hidden;
        }

        .chart-header, .ranking-header, .heatmap-header {
            padding: 1.5rem;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: between;
            align-items: center;
        }

        .chart-title h5, .heatmap-title h5 {
            margin: 0;
            font-weight: 600;
            color: #2c3e50;
        }

        .chart-body, .ranking-body, .heatmap-body {
            padding: 1.5rem;
        }

        .ranking-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .heatmap-container {
            height: 500px;
            border-radius: 10px;
            overflow: hidden;
        }

        .heatmap-info-panel {
            padding: 1rem 1.5rem;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        .info-alert {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 1rem;
            font-size: 0.9rem;
            color: #1565c0;
        }

        .heatmap-legend {
            text-align: center;
        }

        .legend-title {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #495057;
        }

        .legend-items {
            display: flex;
            justify-content: center;
            gap: 1rem;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.8rem;
        }

        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
        }

        .geo-filters-card, .geo-insights-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid #f0f0f0;
            height: 100%;
        }

        .filters-header, .insights-header {
            padding: 1.5rem;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: between;
            align-items: center;
        }

        .filters-body, .insights-body {
            padding: 1.5rem;
        }

        .filter-group {
            margin-bottom: 1.5rem;
        }

        .filter-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.5rem;
            display: block;
        }

        .insights-content {
            max-height: 500px;
            overflow-y: auto;
        }

        .insight-item {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }

        .insight-item.info {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
        }

        .insight-item.success {
            background: #e8f5e8;
            border-left: 4px solid #4caf50;
        }

        .insight-item.warning {
            background: #fff3e0;
            border-left: 4px solid #ff9800;
        }

        .insight-item:hover {
            transform: translateX(5px);
        }

        .insight-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
            flex-shrink: 0;
        }

        .insight-item.info .insight-icon {
            background: #2196f3;
            color: white;
        }

        .insight-item.success .insight-icon {
            background: #4caf50;
            color: white;
        }

        .insight-item.warning .insight-icon {
            background: #ff9800;
            color: white;
        }

        .insight-title {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .insight-text {
            font-size: 0.9rem;
            color: #6c757d;
            line-height: 1.5;
        }

        /* Ranking Items Styles */
        .ranking-list-content {
            max-height: 400px;
            overflow-y: auto;
        }

        .ranking-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            background: white;
        }

        .ranking-item:hover {
            background: #f8f9fa;
            transform: translateX(5px);
        }

        .ranking-item:last-child {
            border-bottom: none;
        }

        .ranking-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1rem;
            margin-left: 1rem;
            flex-shrink: 0;
        }

        .ranking-content {
            flex: 1;
        }

        .ranking-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
            font-size: 1rem;
        }

        .ranking-details {
            display: flex;
            gap: 1rem;
            font-size: 0.85rem;
        }

        .ranking-count {
            color: #495057;
            font-weight: 500;
        }

        .ranking-percentage {
            color: #6c757d;
            background: #e9ecef;
            padding: 0.2rem 0.5rem;
            border-radius: 12px;
            font-weight: 500;
        }

        .ranking-trend {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem;
            font-size: 0.8rem;
            font-weight: 500;
            min-width: 60px;
        }

        .ranking-trend i {
            font-size: 1rem;
        }

        /* Special styling for top 3 rankings */
        .ranking-item:nth-child(1) .ranking-number {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #333;
            box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
        }

        .ranking-item:nth-child(2) .ranking-number {
            background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
            color: #333;
            box-shadow: 0 4px 15px rgba(192, 192, 192, 0.3);
        }

        .ranking-item:nth-child(3) .ranking-number {
            background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(205, 127, 50, 0.3);
        }

        .insight-content p {
            font-size: 0.9rem;
            color: #6c757d;
            margin: 0;
            line-height: 1.5;
        }

        .heatmap-legend {
            background: white;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        .heatmap-legend span {
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-left: 5px;
            border-radius: 50%;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0 text-gray-800">پنل تحلیل داده‌ها</h1>
            <div>
                <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#exportModal">
                    <i class="fas fa-file-export"></i> خروجی گزارش
                </button>
                <div class="btn-group mr-2">
                    <button type="button" class="btn btn-outline-primary" id="refreshData">
                        <i class="fas fa-sync-alt"></i> بروزرسانی
                    </button>
                    <button type="button" class="btn btn-outline-info" id="helpBtn">
                        <i class="fas fa-question-circle"></i> راهنما
                    </button>
                </div>
            </div>
        </div>

        <!-- صفحات آنالیتیکس اصلی -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="btn-group w-100 mb-3" role="group">
                            <a href="<?php echo e(route('admin.analytics.index')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.index') ? 'active' : ''); ?>">
                                <i class="fas fa-tachometer-alt mr-1"></i> داشبورد اصلی
                            </a>
                            <a href="<?php echo e(route('admin.analytics.user')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.user') ? 'active' : ''); ?>">
                                <i class="fas fa-users mr-1"></i> تحلیل رفتار کاربران
                            </a>
                            <a href="<?php echo e(route('admin.analytics.geographic')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.geographic') ? 'active' : ''); ?>">
                                <i class="fas fa-map-marked-alt mr-1"></i> تحلیل جغرافیایی
                            </a>
                            <a href="<?php echo e(route('admin.analytics.predictive')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.predictive') ? 'active' : ''); ?>">
                                <i class="fas fa-chart-line mr-1"></i> تحلیل پیش‌بینی
                            </a>
                            <a href="<?php echo e(route('admin.analytics.performance')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.performance') ? 'active' : ''); ?>">
                                <i class="fas fa-chart-bar mr-1"></i> شاخص‌های عملکرد
                            </a>
                            <a href="<?php echo e(route('admin.analytics.comparisons')); ?>" class="btn btn-primary <?php echo e(request()->routeIs('admin.analytics.comparisons') ? 'active' : ''); ?>">
                                <i class="fas fa-exchange-alt mr-1"></i> مقایسه زمانی داده‌ها
                            </a>
                        </div>
                        <p class="text-muted small text-center">برای مشاهده تحلیل‌های تخصصی روی هر یک از گزینه‌های بالا کلیک کنید.</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Source Alert -->
        <div class="alert alert-info alert-dismissible fade show mb-4" role="alert">
            <strong><i class="fas fa-info-circle"></i> توجه:</strong> تمامی اطلاعات نمایش داده شده در این صفحه به صورت پویا از دیتابیس دریافت می‌شوند و کاملاً واقعی هستند.
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>

        <!-- Stats Overview -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6">
                <div class="card card-analytics bg-primary text-white">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">تعداد مکان‌ها</div>
                                <div class="h5 mb-0 font-weight-bold"><?php echo e(number_format($stats['locations'])); ?></div>
                                <div class="mt-2 text-white-50 small">
                                    <span class="mr-2"><i class="fas fa-arrow-up"></i> 3.5% از ماه قبل</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-map-marker-alt fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6">
                <div class="card card-analytics bg-success text-white">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">تعداد دسته‌بندی‌ها</div>
                                <div class="h5 mb-0 font-weight-bold"><?php echo e(number_format($stats['categories'])); ?></div>
                                <div class="mt-2 text-white-50 small">
                                    <span class="mr-2"><i class="fas fa-check"></i> همه دسته‌ها فعال</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-folder fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6">
                <div class="card card-analytics bg-info text-white">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">تعداد نظرات</div>
                                <div class="h5 mb-0 font-weight-bold"><?php echo e(number_format($stats['ratings'])); ?></div>
                                <div class="mt-2 text-white-50 small">
                                    <span class="mr-2"><i class="fas fa-arrow-up"></i> 12% از ماه قبل</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-star fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6">
                <div class="card card-analytics bg-danger text-white">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1">مکان‌های فعال</div>
                                <div class="h5 mb-0 font-weight-bold"><?php echo e(number_format($stats['active_locations'])); ?></div>
                                <div class="mt-2 text-white-50 small">
                                    <span class="mr-2"><?php echo e(round(($stats['active_locations'] / $stats['locations']) * 100)); ?>% از کل مکان‌ها</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Analytics Tabs -->
        <div class="card card-analytics">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="analyticsTab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="time-tab" data-toggle="tab" href="#timeAnalysis" role="tab">
                            <i class="fas fa-clock mr-1"></i> تحلیل زمانی
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="category-tab" data-toggle="tab" href="#categoryAnalysis" role="tab">
                            <i class="fas fa-folder mr-1"></i> تحلیل دسته‌بندی
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="rating-tab" data-toggle="tab" href="#ratingAnalysis" role="tab">
                            <i class="fas fa-star mr-1"></i> تحلیل نظرات
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="geo-tab" data-toggle="tab" href="#geoAnalysis" role="tab">
                            <i class="fas fa-map-marked-alt mr-1"></i> تحلیل جغرافیایی
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="trends-tab" data-toggle="tab" href="#trendsAnalysis" role="tab">
                            <i class="fas fa-chart-line mr-1"></i> روند رشد
                        </a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="analyticsTabContent">
                    <!-- Time Analysis Tab -->
                    <?php echo $__env->make('admin.analytics.partials.time_analysis', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                    <!-- Category Analysis Tab -->
                    <?php echo $__env->make('admin.analytics.partials.category_analysis', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                    <!-- Rating Analysis Tab -->
                    <?php echo $__env->make('admin.analytics.partials.rating_analysis', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                    <!-- Geographic Analysis Tab -->
                    <?php echo $__env->make('admin.analytics.partials.geography_analysis', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                    <!-- Trends Analysis Tab -->
                    <?php echo $__env->make('admin.analytics.partials.trends_analysis', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1" role="dialog" aria-labelledby="exportModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exportModalLabel">خروجی گزارش</h5>
                    <button type="button" class="close mr-auto ml-0" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="exportForm" action="<?php echo e(route('admin.analytics.export')); ?>" method="post">
                        <?php echo csrf_field(); ?>
                        <div class="form-group">
                            <label for="exportType">نوع گزارش</label>
                            <select class="form-control" id="exportType" name="type">
                                <option value="locations">مکان‌ها</option>
                                <option value="ratings">نظرات</option>
                                <option value="categories">دسته‌بندی‌ها</option>
                                <option value="geographic">جغرافیایی</option>
                                <option value="all">همه داده‌ها</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="exportFormat">فرمت خروجی</label>
                            <select class="form-control" id="exportFormat" name="format">
                                <option value="csv">CSV</option>
                                <option value="excel">Excel</option>
                                <option value="pdf">PDF</option>
                                <option value="json">JSON</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>نمودارها</label>
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="includeCharts" name="include_charts" value="1">
                                <label class="custom-control-label" for="includeCharts">شامل نمودارها</label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">انصراف</button>
                    <button type="button" class="btn btn-primary" id="startExport">شروع خروجی‌گیری</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Help Modal -->
    <div class="modal fade" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="helpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="helpModalLabel">راهنمای پنل تحلیل داده‌ها</h5>
                    <button type="button" class="close mr-auto ml-0" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="accordion" id="helpAccordion">
                        <div class="card">
                            <div class="card-header" id="headingTimeAnalysis">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseTimeAnalysis" aria-expanded="false" aria-controls="collapseTimeAnalysis">
                                        تحلیل زمانی
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseTimeAnalysis" class="collapse" aria-labelledby="headingTimeAnalysis" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>در این بخش می‌توانید روند افزودن مکان‌ها را در بازه‌های زمانی مختلف (روزانه، هفتگی، ماهانه) مشاهده کنید. نمودارها به صورت تعاملی هستند و می‌توانید با موس روی آن‌ها حرکت کرده و اطلاعات دقیق هر نقطه را مشاهده کنید.</p>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header" id="headingCategoryAnalysis">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseCategoryAnalysis" aria-expanded="false" aria-controls="collapseCategoryAnalysis">
                                        تحلیل دسته‌بندی
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseCategoryAnalysis" class="collapse" aria-labelledby="headingCategoryAnalysis" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>در این بخش توزیع مکان‌ها در دسته‌بندی‌های مختلف و همچنین روند رشد هر دسته را مشاهده می‌کنید. می‌توانید با کلیک روی دکمه‌های بالای نمودار بین حالت‌های مختلف نمایش تغییر وضعیت دهید.</p>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header" id="headingRatingAnalysis">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseRatingAnalysis" aria-expanded="false" aria-controls="collapseRatingAnalysis">
                                        تحلیل نظرات
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseRatingAnalysis" class="collapse" aria-labelledby="headingRatingAnalysis" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>این بخش به تحلیل نظرات کاربران اختصاص دارد. توزیع امتیازات، روند نظردهی و میانگین امتیازات را در دوره‌های زمانی مختلف مشاهده می‌کنید.</p>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header" id="headingGeoAnalysis">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseGeoAnalysis" aria-expanded="false" aria-controls="collapseGeoAnalysis">
                                        تحلیل جغرافیایی
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseGeoAnalysis" class="collapse" aria-labelledby="headingGeoAnalysis" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>در تحلیل جغرافیایی، توزیع مکان‌ها را بر روی نقشه مشاهده می‌کنید. نقشه حرارتی ایران، تراکم مکان‌ها در استان‌ها و شهرها را نمایش می‌دهد. می‌توانید با بزرگنمایی نقشه، جزئیات بیشتری را مشاهده کنید.</p>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header" id="headingTrendsAnalysis">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseTrendsAnalysis" aria-expanded="false" aria-controls="collapseTrendsAnalysis">
                                        روند رشد
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseTrendsAnalysis" class="collapse" aria-labelledby="headingTrendsAnalysis" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>در این بخش روند رشد کلی سیستم و همچنین درصد رشد هر دسته‌بندی را مشاهده می‌کنید. نمودارهای این بخش به شما کمک می‌کنند تا دسته‌بندی‌های پرطرفدار و در حال رشد را شناسایی کنید.</p>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header" id="headingExport">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-right collapsed" type="button" data-toggle="collapse" data-target="#collapseExport" aria-expanded="false" aria-controls="collapseExport">
                                        خروجی گزارش
                                    </button>
                                </h2>
                            </div>
                            <div id="collapseExport" class="collapse" aria-labelledby="headingExport" data-parent="#helpAccordion">
                                <div class="card-body">
                                    <p>با کلیک بر روی دکمه «خروجی گزارش» می‌توانید داده‌های مورد نظر خود را در قالب‌های مختلف (CSV، Excel، PDF یا JSON) دریافت کنید. می‌توانید نوع گزارش را انتخاب کرده و در صورت تمایل نمودارها را نیز در گزارش خود بگنجانید.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">بستن</button>
                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <!-- Redundant ApexCharts import with defer to ensure it loads -->
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@3.35.0/dist/apexcharts.min.js" defer></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="https://unpkg.com/leaflet.heat@0.2.0/dist/leaflet-heat.js"></script>

    <!-- Heat Layer Optimizer is already loaded in the main layout -->

    <script>
        // Safe wrapper for ApexCharts initialization to handle null DOM elements
        function createChart(selector, options) {
            const element = document.querySelector(selector);
            if (!element) {
                console.warn(`Chart container not found: ${selector}`);
                return null;
            }

            try {
                // COMPLETELY DISABLE TOOLTIPS to prevent classList errors
                options.tooltip = {
                    enabled: false
                };

                // Add null safety for animations
                if (!options.chart) {
                    options.chart = {};
                }

                options.chart = {
                    ...options.chart,
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        },
                        dynamicAnimation: {
                            enabled: true,
                            speed: 350
                        }
                    },
                    // Add empty event handlers to prevent errors
                    events: {}
                };

                // Create chart without any event handlers that might cause errors
                const chart = new ApexCharts(element, options);
                chart.render();
                return chart;
            } catch (error) {
                console.error(`Error creating chart for ${selector}:`, error);
                return null;
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM Loaded, preparing tabs');

            // اضافه کردن onclick به تمام تب‌ها
            document.querySelectorAll('.nav-tabs a').forEach(function(tab) {
                tab.setAttribute('onclick', 'activateTab("' + tab.getAttribute('href').substring(1) + '"); return false;');
            });

            // فعال‌سازی تب از URL در بارگذاری صفحه
            const hash = window.location.hash;
            if (hash) {
                setTimeout(function() {
                    window.activateTab(hash.substring(1));
                }, 100);
            } else {
                // اگر هش نبود، تب اول را فعال کن
                const firstTabHref = document.querySelector('.nav-tabs a:first-child').getAttribute('href');
                const firstTabId = firstTabHref.substring(1);

                setTimeout(function() {
                    window.activateTab(firstTabId);
                }, 100);
            }

            // تابع فعال‌سازی تب
            window.activateTab = function(tabId) {
                console.log('Activating tab: ' + tabId);

                // Clean up map if we're switching away from geoAnalysis tab
                const isLeavingGeoTab = document.querySelector('#geoAnalysis.active') !== null && tabId !== 'geoAnalysis';
                if (isLeavingGeoTab && window.iranHeatmap) {
                    console.log('Cleaning up map when leaving geo tab');
                    window.iranHeatmap.remove();
                    window.iranHeatmap = null;
                }

                // غیرفعال کردن همه تب‌ها
                document.querySelectorAll('.nav-tabs a').forEach(function(tab) {
                    tab.classList.remove('active');
                });

                document.querySelectorAll('.tab-pane').forEach(function(pane) {
                    pane.classList.remove('active', 'show');
                });

                // فعال کردن تب موردنظر
                var selectedTab = document.querySelector('.nav-tabs a[href="#' + tabId + '"]');
                var selectedPane = document.getElementById(tabId);

                if (selectedTab && selectedPane) {
                    selectedTab.classList.add('active');
                    selectedPane.classList.add('active', 'show');

                    // تغییر URL
                    history.pushState(null, null, '#' + tabId);

                    // Track tab initializations to prevent duplication
                    window.initializedTabs = window.initializedTabs || {};

                    // اگر تب فعال شده تب تحلیل جغرافیایی است و هنوز مقداردهی نشده
                    if (tabId === 'geoAnalysis' && !window.initializedTabs[tabId]) {
                        window.initializedTabs[tabId] = true;
                        console.log('Geographic tab activated, preparing map...');

                        // Show the tab content first to ensure containers are visible
                        selectedPane.style.display = 'block';

                        // Delay map initialization to ensure container is rendered
                        setTimeout(function() {
                            const activeChartType = document.querySelector('[data-geography-chart].active')?.getAttribute('data-geography-chart') || 'heatmap';

                            // ابتدا همه کانتینرهای جغرافیایی را مخفی کنیم
                            document.querySelectorAll('.geography-chart').forEach(container => {
                                container.classList.add('d-none');
                            });

                            // سپس کانتینر مورد نظر را نمایش دهیم
                            document.querySelectorAll(`[data-chart-type="${activeChartType}"]`).forEach(container => {
                                container.classList.remove('d-none');
                                // Force reflow
                                void container.offsetHeight;
                            });

                            // Force map container to be visible with sufficient dimensions
                            if (activeChartType === 'heatmap') {
                                const mapContainer = document.getElementById('iran-heatmap');
                                if (mapContainer) {
                                    mapContainer.style.display = 'block';
                                    mapContainer.style.height = '500px';
                                    mapContainer.style.width = '100%';
                                    mapContainer.style.position = 'relative';
                                    void mapContainer.offsetHeight; // Force reflow
                                }
                            }

                            // فراخوانی تابع رندر مناسب
                            if (activeChartType === 'provinces') {
                                renderProvincesChart();
                                renderTopProvinces();
                            } else if (activeChartType === 'cities') {
                                renderCitiesChart();
                                renderTopCities();
                            } else if (activeChartType === 'heatmap') {
                                // Longer delay for heatmap to ensure DOM is ready
                                setTimeout(() => {
                                    renderIranHeatmap();
                                }, 300);
                            }
                        }, 200);
                    }
                    // If we're switching to geoAnalysis tab and it's already initialized, check for pending heat layer
                    else if (tabId === 'geoAnalysis' && window.heatLayerPending && window.iranHeatmap) {
                        console.log('GeoAnalysis tab activated, checking for pending heat layer...');

                        // Show the tab content to ensure containers are visible
                        selectedPane.style.display = 'block';

                        // Check if we should handle a pending heat layer
                        if (document.querySelector('[data-geography-chart].active')?.getAttribute('data-geography-chart') === 'heatmap') {
                            setTimeout(() => {
                                try {
                                    console.log('Adding pending heat layer to map...');

                                    // Make sure the map is properly sized
                                    window.iranHeatmap.invalidateSize(true);

                                    // Process the pending heat data if available
                                    if (window.heatLayerData && window.heatLayerData.length > 0) {
                                        const processedData = [];

                                        window.heatLayerData.forEach(point => {
                                            let lat, lng, intensity;

                                            // Handle array format [lat, lng, intensity]
                                            if (Array.isArray(point) && point.length >= 2) {
                                                lat = parseFloat(point[0]);
                                                lng = parseFloat(point[1]);
                                                intensity = point.length > 2 ? parseFloat(point[2]) : 1;
                                            }
                                            // Handle object format {lat, lng, intensity}
                                            else if (point && typeof point === 'object') {
                                                lat = parseFloat(point.lat || 0);
                                                lng = parseFloat(point.lng || 0);
                                                intensity = parseFloat(point.intensity || 1);
                                            }

                                            // Validate coordinates
                                            if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
                                                processedData.push([lat, lng, intensity]);
                                            }
                                        });

                                        if (processedData.length > 0) {
                                            // Add optimized heat layer to map
                                            const heat = createOptimizedHeatLayer(processedData, {
                                                radius: 25,
                                                blur: 15,
                                                maxZoom: 10,
                                                minOpacity: 0.3
                                            });

                                            if (heat) {
                                                heat.addTo(window.iranHeatmap);
                                                console.log('Pending optimized heat layer added successfully');
                                            }

                                            // Clear pending flags
                                            window.heatLayerPending = false;
                                            window.heatLayerData = null;
                                        }
                                    }
                                } catch (e) {
                                    console.error('Error adding pending heat layer:', e);
                                }
                            }, 500);
                        }
                    }
                    // Ensure time analysis tab is initialized if needed
                    else if (tabId === 'timeAnalysis' && !window.initializedTabs[tabId]) {
                        window.initializedTabs[tabId] = true;
                        console.log('Time analysis tab activated, initializing charts...');
                        initTimeAnalysisCharts();
                        // شروع بروزرسانی داده‌های لحظه‌ای
                        startRealtimeUpdates();
                    }

                    console.log('Tab activated successfully');
                } else {
                    console.error('Tab or pane not found: ' + tabId);
                }
            };

            // مقداردهی اولیه نمودارها - با تأخیر بیشتر برای اطمینان از اینکه تب‌ها آماده شده‌اند
            setTimeout(function() {
                console.log('Initializing charts');
                // Get the active tab ID
                const activeTabId = window.location.hash.substring(1) || 'timeAnalysis';
                window.initializedTabs = window.initializedTabs || {};

                // Only initialize the currently active tab to prevent duplication
                if (activeTabId === 'timeAnalysis' && !window.initializedTabs[activeTabId]) {
                    window.initializedTabs[activeTabId] = true;
                    initTimeAnalysisCharts();
                }
                else if (activeTabId === 'categoryAnalysis' && !window.initializedTabs[activeTabId]) {
                    window.initializedTabs[activeTabId] = true;
                    initCategoryAnalysisCharts();
                }
                else if (activeTabId === 'ratingAnalysis' && !window.initializedTabs[activeTabId]) {
                    window.initializedTabs[activeTabId] = true;
                    initRatingAnalysisCharts();
                }
                else if (activeTabId === 'geoAnalysis' && !window.initializedTabs[activeTabId]) {
                    window.initializedTabs[activeTabId] = true;
                    initGeoAnalysisCharts();
                }
                else if (activeTabId === 'trendsAnalysis' && !window.initializedTabs[activeTabId]) {
                    window.initializedTabs[activeTabId] = true;
                    initTrendsAnalysisCharts();
                }
            }, 300);

            // Ensure time analysis charts are always initialized
            setTimeout(function() {
                // Double-check if time analysis tab is active but charts aren't initialized
                if (document.querySelector('#timeAnalysis.active.show') && !window.timeChartsInitialized) {
                    console.log('Time analysis tab is active but charts not initialized, fixing...');
                    initTimeAnalysisCharts();
                }
            }, 1000);

            // رویداد خروجی‌گیری
            document.getElementById('startExport').addEventListener('click', function() {
                const form = document.getElementById('exportForm');
                const formData = new FormData(form);

                fetch(form.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('خروجی با موفقیت شروع شد.');
                        $('#exportModal').modal('hide');
                    } else {
                        alert('خطا در خروجی‌گیری: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('خطا در ارتباط با سرور.');
                });
            });

            // رویداد دکمه راهنما
            document.getElementById('helpBtn').addEventListener('click', function() {
                $('#helpModal').modal('show');
            });

            // Manejar refreshData
            document.getElementById('refreshData').addEventListener('click', function() {
                // Show loading spinner on the button
                const btn = this;
                const originalHTML = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> در حال به‌روزرسانی...';
                btn.disabled = true;

                // Call the refresh API
                fetch('<?php echo e(route('admin.analytics.refresh')); ?>', {
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success notification
                        Swal.fire({
                            title: 'به‌روزرسانی موفق',
                            text: data.message,
                            icon: 'success',
                            confirmButtonText: 'ادامه'
                        }).then(() => {
                            // Reload page to show fresh data
                            location.reload();
                        });
                    } else {
                        // Show error message
                        Swal.fire({
                            title: 'خطا',
                            text: data.message,
                            icon: 'error',
                            confirmButtonText: 'تلاش مجدد'
                        });
                        // Restore button
                        btn.innerHTML = originalHTML;
                        btn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error refreshing analytics data:', error);
                    Swal.fire({
                        title: 'خطا در به‌روزرسانی',
                        text: 'مشکلی در ارتباط با سرور رخ داده است. لطفاً مجدداً تلاش کنید.',
                        icon: 'error',
                        confirmButtonText: 'تلاش مجدد'
                    });
                    // Restore button
                    btn.innerHTML = originalHTML;
                    btn.disabled = false;
                });
            });

            // Definisi fungsi rendering peta panas Iran
            window.renderIranHeatmap = function() {
                try {
                    // Add a flag to prevent multiple simultaneous initializations
                    if (window.isRenderingHeatmap) {
                        console.log('Heatmap already being rendered, skipping duplicate call');
                        return;
                    }

                    // Set the flag to indicate rendering has started
                    window.isRenderingHeatmap = true;

                    console.log('Starting heatmap rendering from window.renderIranHeatmap...');

                    // First ensure the heatmap container is visible
                    const heatmapContainer = document.getElementById('heatmap-container');
                    if (heatmapContainer && heatmapContainer.classList.contains('d-none')) {
                        console.log('Removing d-none class from heatmap container');
                        heatmapContainer.classList.remove('d-none');
                    }

                    // Check if element exists
                    const mapContainer = document.getElementById('iran-heatmap');
                    if (!mapContainer) {
                        console.error('Map container not found!');
                        window.isRenderingHeatmap = false; // Reset flag
                        return;
                    }

                    // RESET: Always clear the map container contents
                    mapContainer.innerHTML = '';

                    // RESTART: Remove existing map instance
                    if (window.iranHeatmap) {
                        console.log('Removing existing map instance');
                        window.iranHeatmap.remove();
                        window.iranHeatmap = null;
                    }

                    // Set proper dimensions for the map container and make sure it's visible
                    mapContainer.style.height = '500px';
                    mapContainer.style.width = '100%';
                    mapContainer.style.position = 'relative';
                    mapContainer.style.display = 'block';  // Ensure it's displayed
                    mapContainer.style.visibility = 'visible'; // Ensure it's visible

                    // Force layout recalculation
                    void mapContainer.offsetWidth;

                    // Create a new unique map container with specific styling
                    const newMapId = 'iran-heatmap-' + Date.now();
                    const newMapDiv = document.createElement('div');
                    newMapDiv.id = newMapId;
                    newMapDiv.style.height = '100%';
                    newMapDiv.style.width = '100%';
                    newMapDiv.style.display = 'block';
                    newMapDiv.style.visibility = 'visible';
                    mapContainer.appendChild(newMapDiv);

                    console.log('New map container created with id:', newMapId);

                    // Check if Leaflet is properly loaded
                    if (typeof L === 'undefined') {
                        console.error('Leaflet library is not loaded!');
                        newMapDiv.innerHTML = `
                            <div class="alert alert-danger text-center p-5">
                                <h4>خطای کتابخانه</h4>
                                <p>کتابخانه Leaflet به درستی بارگذاری نشده است.</p>
                            </div>
                        `;
                        return;
                    }

                    // Add a longer delay to ensure the DOM is fully updated
                    setTimeout(() => {
                        try {
                            const mapElement = document.getElementById(newMapId);
                            if (!mapElement) {
                                throw new Error('Map div element not found after DOM update');
                            }

                            // Force another layout recalculation
                            void mapElement.offsetHeight;

                            // Check if the container has dimensions and force them if needed
                            const rect = mapElement.getBoundingClientRect();
                            if (rect.width === 0 || rect.height === 0) {
                                console.log('Map container has zero dimensions, attempting to fix...');

                                // Force dimensions with !important
                                mapElement.setAttribute('style', 'height: 500px !important; width: 100% !important; display: block !important; visibility: visible !important;');

                                // Force layout recalculation once more
                                void mapElement.offsetHeight;

                                // Check again after forcing dimensions
                                const newRect = mapElement.getBoundingClientRect();
                                if (newRect.width === 0 || newRect.height === 0) {
                                    console.log('Map container still has zero dimensions. Deferring heat layer rendering.');
                                    // Set a flag to indicate we need to render the heat layer later
                                    window.heatLayerPending = true;
                                    window.heatLayerData = window.heatLayerData || [];
                                }
                            }

                            // Iran center coordinates
                            const iranCenter = [32.4279, 53.6880];

                            // Create the map on the new element
                            const map = L.map(newMapId, {
                                center: iranCenter,
                                zoom: 5,
                                zoomControl: true,
                                minZoom: 4,
                                maxZoom: 10
                            });

                            // Store map instance
                            window.iranHeatmap = map;
                            console.log('Map created successfully on new container');

                            // Dispatch custom event to notify other components that map is ready
                            window.dispatchEvent(new CustomEvent('mapCreated', {
                                detail: { mapId: newMapId, mapType: 'iranHeatmap' }
                            }));

                            // Set up a ResizeObserver to monitor map container dimensions
                            // This will help handle deferred heat layer rendering when tab becomes visible
                            if (typeof ResizeObserver !== 'undefined') {
                                // Clean up any existing observers
                                if (window.mapResizeObserver) {
                                    window.mapResizeObserver.disconnect();
                                }

                                window.mapResizeObserver = new ResizeObserver(entries => {
                                    for (let entry of entries) {
                                        const { width, height } = entry.contentRect;
                                        if (width > 0 && height > 0 && window.heatLayerPending && window.heatLayerData) {
                                            // Map has dimensions now, try to add the heat layer
                                            console.log('Map size changed to valid dimensions, attempting to add heat layer');
                                            map.invalidateSize(true);

                                            setTimeout(() => {
                                                try {
                                                    // Process pending heat data
                                                    const processedData = [];

                                                    window.heatLayerData.forEach(point => {
                                                        let lat, lng, intensity;

                                                        // Handle array format [lat, lng, intensity]
                                                        if (Array.isArray(point) && point.length >= 2) {
                                                            lat = parseFloat(point[0]);
                                                            lng = parseFloat(point[1]);
                                                            intensity = point.length > 2 ? parseFloat(point[2]) : 1;
                                                        }
                                                        // Handle object format {lat, lng, intensity}
                                                        else if (point && typeof point === 'object') {
                                                            lat = parseFloat(point.lat || 0);
                                                            lng = parseFloat(point.lng || 0);
                                                            intensity = parseFloat(point.intensity || 1);
                                                        }

                                                        // Validate coordinates
                                                        if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
                                                            processedData.push([lat, lng, intensity]);
                                                        }
                                                    });

                                                    if (processedData.length > 0) {
                                                        // Add optimized heat layer to map
                                                        const heat = createOptimizedHeatLayer(processedData, {
                                                            radius: 25,
                                                            blur: 15,
                                                            maxZoom: 10,
                                                            minOpacity: 0.3
                                                        });

                                                        if (heat) {
                                                            heat.addTo(map);
                                                            console.log('Optimized heat layer added by ResizeObserver');
                                                        }

                                                        // Clear pending flags
                                                        window.heatLayerPending = false;
                                                        window.heatLayerData = null;

                                                        // Remove observer once heat layer is added
                                                        window.mapResizeObserver.disconnect();
                                                        window.mapResizeObserver = null;
                                                    }
                                                } catch (e) {
                                                    console.error('Error adding heat layer from observer:', e);
                                                }
                                            }, 200);
                                        }
                                    }
                                });

                                // Observe the map container
                                window.mapResizeObserver.observe(mapElement);
                            }

                            // Add OpenStreetMap layer
                            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                            }).addTo(map);
                            console.log('Base tile layer added');

                            // Get heatmap data
                            const heatData = <?php echo json_encode($geographicData['heatmap'] ?? [], 15, 512) ?>;
                            console.log('Heatmap data loaded:', heatData ? heatData.length : 0, 'points');

                            // Make sure the map is fully rendered before adding the heat layer
                            setTimeout(() => {
                                try {
                                    // Check if map container has proper dimensions before proceeding
                                    const mapRect = mapElement.getBoundingClientRect();
                                    if (mapRect.width === 0 || mapRect.height === 0) {
                                        console.warn('Map container still has zero dimensions. Deferring heat layer rendering.');

                                        // Set a flag to indicate rendering is incomplete
                                        window.heatLayerPending = true;
                                        window.heatLayerData = heatData;

                                        // Reset the rendering flag to allow future attempts
                                        window.isRenderingHeatmap = false;
                                        return;
                                    }

                                    // Ensure map is valid and fully initialized
                                    map.invalidateSize();

                                    // IMPROVED: Better data processing for heat points
                                    const processedHeatData = [];

                                    // Process all types of input formats
                                    if (heatData && heatData.length > 0) {
                                        heatData.forEach(point => {
                                            let lat, lng, intensity;

                                            // Handle array format [lat, lng, intensity]
                                            if (Array.isArray(point) && point.length >= 2) {
                                                lat = parseFloat(point[0]);
                                                lng = parseFloat(point[1]);
                                                intensity = point.length > 2 ? parseFloat(point[2]) : 1;
                                            }
                                            // Handle object format {lat, lng, intensity}
                                            else if (point && typeof point === 'object') {
                                                lat = parseFloat(point.lat || 0);
                                                lng = parseFloat(point.lng || 0);
                                                intensity = parseFloat(point.intensity || 1);
                                            }

                                            // Validate coordinates
                                            if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
                                                processedHeatData.push([lat, lng, intensity]);
                                            } else {
                                                console.warn('Invalid heat point skipped:', point);
                                            }
                                        });
                                    }

                                    console.log('Processed heat data points:', processedHeatData.length);

                                    // Only add the heat layer if we have valid points and the map has dimensions
                                    if (processedHeatData.length > 0) {
                                        try {
                                            // One final check on map dimensions
                                            map.invalidateSize(true);

                                            // Add optimized heat layer to map
                                            const heat = createOptimizedHeatLayer(processedHeatData, {
                                                radius: 25,
                                                blur: 15,
                                                maxZoom: 10,
                                                minOpacity: 0.3
                                            });

                                            if (heat) {
                                                heat.addTo(map);
                                            }

                                            console.log('Heat layer added successfully');

                                            // Clear any pending heat layer flags
                                            window.heatLayerPending = false;
                                            window.heatLayerData = null;
                                        } catch (heatError) {
                                            console.error('Error adding heat layer:', heatError);

                                            // Store data for later retry when tab is activated
                                            window.heatLayerPending = true;
                                            window.heatLayerData = processedHeatData;

                                            const errorControl = L.control({position: 'bottomleft'});
                                            errorControl.onAdd = function() {
                                                const div = L.DomUtil.create('div', 'info');
                                                div.innerHTML = `<div class="alert alert-warning p-2">خطا در افزودن لایه حرارتی. نمایش دوباره تب را امتحان کنید.</div>`;
                                                return div;
                                            };
                                            errorControl.addTo(map);
                                        }
                                    } else {
                                        console.warn('No valid heat points available');
                                        // Show message in map if no valid points
                                        const noDataControl = L.control({position: 'bottomleft'});
                                        noDataControl.onAdd = function() {
                                            const div = L.DomUtil.create('div', 'info');
                                            div.innerHTML = '<div class="alert alert-warning p-2">داده‌ای برای نمایش وجود ندارد</div>';
                                            return div;
                                        };
                                        noDataControl.addTo(map);
                                    }

                                } catch (error) {
                                    console.error('Error adding heat layer:', error);
                                    const errorControl = L.control({position: 'bottomleft'});
                                    errorControl.onAdd = function() {
                                        const div = L.DomUtil.create('div', 'info');
                                        div.innerHTML = `<div class="alert alert-danger p-2">خطا در افزودن لایه حرارتی: ${error.message}</div>`;
                                        return div;
                                    };
                                    errorControl.addTo(map);

                                    // Reset the flag after error
                                    window.isRenderingHeatmap = false;
                                }
                            }, 500);

                        } catch (error) {
                            console.error('Error creating map:', error);
                            const mapElement = document.getElementById(newMapId);
                            if (mapElement) {
                                mapElement.innerHTML = `
                                    <div class="alert alert-danger text-center p-5">
                                        <h4>خطا در ایجاد نقشه</h4>
                                        <p>${error.message}</p>
                                    </div>
                                `;
                            }
                        }
                    }, 500); // Increased timeout for DOM to fully update

                } catch (error) {
                    console.error('Fatal error in renderIranHeatmap:', error);
                    window.isRenderingHeatmap = false; // Reset flag on error

                    // Show error message on the page
                    const mapContainer = document.getElementById('iran-heatmap');
                    if (mapContainer) {
                        mapContainer.innerHTML = `
                            <div class="alert alert-danger text-center p-5">
                                <h4>خطای سیستم</h4>
                                <p>${error.message}</p>
                            </div>
                        `;
                    }
                }

                // Reset the flag after all operations complete (at the end of the function)
                setTimeout(() => {
                    window.isRenderingHeatmap = false;
                }, 1000);
            }
        });

        // Inicializar gráficos de análisis temporal
        function initTimeAnalysisCharts() {
            // Prevent multiple initializations
            if (window.timeChartsInitialized) {
                console.log('Time charts already initialized, skipping duplicate initialization');
                return;
            }

            console.log('Initializing time analysis charts');

            // Check if ApexCharts is defined
            if (typeof ApexCharts === 'undefined') {
                console.error('ApexCharts library is not loaded! Adding script tag dynamically.');
                // Try to load ApexCharts dynamically
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/apexcharts';
                script.onload = function() {
                    console.log('ApexCharts loaded dynamically, reinitializing charts');
                    initTimeAnalysisCharts();
                };
                document.head.appendChild(script);
                return;
            }

            window.timeChartsInitialized = true;

            // Add time filter buttons functionality
            const timeFilterButtons = document.querySelectorAll('[data-time-filter]');
            const timeCharts = document.querySelectorAll('.time-chart');

            timeFilterButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // Remove active class from all buttons
                    timeFilterButtons.forEach(btn => btn.classList.remove('active'));

                    // Add active class to clicked button
                    this.classList.add('active');

                    // Hide all charts
                    timeCharts.forEach(chart => chart.style.display = 'none');

                    // Show selected chart
                    const selectedFilter = this.getAttribute('data-time-filter');
                    document.getElementById(`${selectedFilter}Analysis`).style.display = 'block';
                });
            });

            try {
                // Make the daily analysis container visible by default
                const dailyAnalysis = document.getElementById('dailyAnalysis');
                if (dailyAnalysis) {
                    dailyAnalysis.style.display = 'block';
                }

                // Check if chart containers exist
                const dailyChartElement = document.querySelector("#dailyChart");
                if (!dailyChartElement) {
                    console.error('Daily chart container not found!');
                    return;
                }

                // Daily Chart
                const dailyOptions = {
                    series: [{
                        name: 'مکان‌ها',
                        data: <?php echo json_encode($timeframeAnalytics['daily']['data'], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'area',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                        toolbar: {
                            show: true,
                        },
                        zoom: {
                            enabled: true
                        }
                    },
                    dataLabels: {
                        enabled: false
                    },
                    stroke: {
                        curve: 'smooth',
                        width: 2
                    },
                    fill: {
                        type: 'gradient',
                        gradient: {
                            shadeIntensity: 1,
                            opacityFrom: 0.7,
                            opacityTo: 0.3,
                            stops: [0, 90, 100]
                        }
                    },
                    xaxis: {
                        categories: <?php echo json_encode($timeframeAnalytics['daily']['labels'], 15, 512) ?>,
                        labels: {
                            rotate: -45,
                            style: {
                                fontSize: '10px'
                            }
                        }
                    },
                    yaxis: {
                        labels: {
                            formatter: function (val) {
                                return val.toFixed(0);
                            }
                        }
                    },
                    colors: ['#4e73df'],
                    markers: {
                        size: 4
                    },
                    tooltip: {
                        x: {
                            format: 'dd MMM yyyy'
                        }
                    },
                    title: {
                        text: 'روند روزانه افزودن مکان‌ها (30 روز اخیر)',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                console.log('Creating daily chart...');
                const dailyChart = new ApexCharts(dailyChartElement, dailyOptions);
                dailyChart.render();
                console.log('Daily chart rendered successfully');

                // Continue with other charts only if their containers exist
                const weeklyChartElement = document.querySelector("#weeklyChart");
                if (weeklyChartElement) {
                    // Weekly Chart
                    const weeklyOptions = {
                        series: [{
                            name: 'مکان‌ها',
                            data: <?php echo json_encode($timeframeAnalytics['weekly']['data'], 15, 512) ?>
                        }],
                        chart: {
                            height: 350,
                            type: 'bar',
                            fontFamily: 'IRANSans, tahoma, sans-serif',
                        },
                        plotOptions: {
                            bar: {
                                borderRadius: 4,
                                horizontal: false,
                                columnWidth: '70%',
                            }
                        },
                        dataLabels: {
                            enabled: false
                        },
                        stroke: {
                            show: true,
                            width: 2,
                            colors: ['transparent']
                        },
                        xaxis: {
                            categories: <?php echo json_encode($timeframeAnalytics['weekly']['labels'], 15, 512) ?>,
                            labels: {
                                rotate: -45,
                                style: {
                                    fontSize: '10px'
                                }
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'تعداد'
                            },
                            labels: {
                                formatter: function (val) {
                                    return val.toFixed(0);
                                }
                            }
                        },
                        fill: {
                            opacity: 1
                        },
                        colors: ['#1cc88a'],
                        tooltip: {
                            y: {
                                formatter: function (val) {
                                    return val + " مکان";
                                }
                            }
                        },
                        title: {
                            text: 'روند هفتگی افزودن مکان‌ها (12 هفته اخیر)',
                            align: 'center',
                            style: {
                                fontSize: '14px',
                                fontWeight: 'bold',
                            }
                        }
                    };

                    console.log('Creating weekly chart...');
                    const weeklyChart = new ApexCharts(weeklyChartElement, weeklyOptions);
                    weeklyChart.render();
                    console.log('Weekly chart rendered successfully');
                }

                // Monthly Chart
                const monthlyChartElement = document.querySelector("#monthlyChart");
                if (monthlyChartElement) {
                    const monthlyOptions = {
                        series: [{
                            name: 'مکان‌ها',
                            data: <?php echo json_encode($timeframeAnalytics['monthly']['data'], 15, 512) ?>
                        }],
                        chart: {
                            height: 350,
                            type: 'line',
                            fontFamily: 'IRANSans, tahoma, sans-serif',
                        },
                        dataLabels: {
                            enabled: true,
                            formatter: function (val) {
                                return val;
                            },
                            offsetY: -20,
                            style: {
                                fontSize: '12px',
                                colors: ["#304758"]
                            }
                        },
                        stroke: {
                            width: 3,
                            curve: 'smooth'
                        },
                        xaxis: {
                            categories: <?php echo json_encode($timeframeAnalytics['monthly']['labels'], 15, 512) ?>,
                        },
                        yaxis: {
                            labels: {
                                formatter: function (val) {
                                    return val.toFixed(0);
                                }
                            }
                        },
                        markers: {
                            size: 6,
                            strokeWidth: 3,
                            strokeColors: "#fff",
                            hover: {
                                size: 8
                            }
                        },
                        colors: ['#4e73df'],
                        title: {
                            text: 'روند ماهانه افزودن مکان‌ها (12 ماه اخیر)',
                            align: 'center',
                            style: {
                                fontSize: '14px',
                                fontWeight: 'bold',
                            }
                        }
                    };

                    console.log('Creating monthly chart...');
                    const monthlyChart = new ApexCharts(monthlyChartElement, monthlyOptions);
                    monthlyChart.render();
                    console.log('Monthly chart rendered successfully');
                }

                // Yearly Chart
                const yearlyChartElement = document.querySelector("#yearlyChart");
                if (yearlyChartElement) {
                    const yearlyOptions = {
                        series: [{
                            name: 'مکان‌ها',
                            data: <?php echo json_encode($timeframeAnalytics['yearly']['data'], 15, 512) ?>
                        }],
                        chart: {
                            height: 350,
                            type: 'bar',
                            fontFamily: 'IRANSans, tahoma, sans-serif',
                        },
                        plotOptions: {
                            bar: {
                                distributed: true,
                                borderRadius: 4,
                                horizontal: false,
                                columnWidth: '40%',
                            }
                        },
                        dataLabels: {
                            enabled: true,
                            formatter: function (val) {
                                return val;
                            },
                            style: {
                                fontSize: '12px',
                            }
                        },
                        legend: {
                            show: false
                        },
                        xaxis: {
                            categories: <?php echo json_encode($timeframeAnalytics['yearly']['labels'], 15, 512) ?>,
                        },
                        yaxis: {
                            labels: {
                                formatter: function (val) {
                                    return val.toFixed(0);
                                }
                            }
                        },
                        colors: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b'],
                        title: {
                            text: 'مقایسه سالانه افزودن مکان‌ها (5 سال اخیر)',
                            align: 'center',
                            style: {
                                fontSize: '14px',
                                fontWeight: 'bold',
                            }
                        }
                    };

                    console.log('Creating yearly chart...');
                    const yearlyChart = new ApexCharts(yearlyChartElement, yearlyOptions);
                    yearlyChart.render();
                    console.log('Yearly chart rendered successfully');
                }
            } catch (error) {
                console.error('Error initializing time analysis charts:', error);
            }
        }

        // Funciones para inicializar resto de gráficos
        function initCategoryAnalysisCharts() {
            // Verifikasi apakah elemen categoryDistributionChart ada di DOM
            if (document.querySelector("#categoryDistributionChart")) {
                const categoryDistOptions = {
                    series: [{
                        name: 'تعداد مکان‌ها',
                        data: <?php echo json_encode($categoryAnalytics['distribution']['data'] ?? [], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'bar',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            distributed: true,
                            horizontal: true,
                        }
                    },
                    colors: <?php echo json_encode($categoryAnalytics['distribution']['colors'] ?? [], 15, 512) ?>,
                    dataLabels: {
                        enabled: false
                    },
                    xaxis: {
                        categories: <?php echo json_encode($categoryAnalytics['distribution']['labels'] ?? [], 15, 512) ?>,
                    },
                    title: {
                        text: 'توزیع مکان‌ها بر اساس دسته‌بندی',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#categoryDistributionChart", categoryDistOptions);
            }

            // Verifikasi apakah elemen categoryGrowthChart ada di DOM
            if (document.querySelector("#categoryGrowthChart")) {
                const categoryGrowthOptions = {
                    series: [{
                        name: 'درصد رشد',
                        data: <?php echo json_encode($categoryAnalytics['growth']['data'] ?? [], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'bar',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            horizontal: false,
                        }
                    },
                    dataLabels: {
                        enabled: true,
                        formatter: function (val) {
                            return val + '%';
                        }
                    },
                    xaxis: {
                        categories: <?php echo json_encode($categoryAnalytics['growth']['labels'] ?? [], 15, 512) ?>,
                        labels: {
                            rotate: -45,
                            style: {
                                fontSize: '10px'
                            }
                        }
                    },
                    colors: ['#1cc88a'],
                    title: {
                        text: 'درصد رشد دسته‌بندی‌ها در ماه اخیر',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#categoryGrowthChart", categoryGrowthOptions);
            }
        }

        function initRatingAnalysisCharts() {
            // Implementación de las gráficas de calificaciones
            // Verifikasi apakah elemen ratingDistributionChart ada di DOM
            if (document.querySelector("#ratingDistributionChart")) {
                const ratingDistOptions = {
                    series: [{
                        name: 'تعداد نظرات',
                        data: <?php echo json_encode($ratingAnalytics['distribution']['data'] ?? [], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'bar',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            distributed: true,
                        }
                    },
                    colors: ['#f6c23e', '#f6c23e', '#f6c23e', '#f6c23e', '#f6c23e'],
                    dataLabels: {
                        enabled: true
                    },
                    xaxis: {
                        categories: <?php echo json_encode($ratingAnalytics['distribution']['labels'] ?? [], 15, 512) ?>,
                    },
                    title: {
                        text: 'توزیع امتیازات (از 1 تا 5)',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#ratingDistributionChart", ratingDistOptions);
            }

            // Verifikasi apakah elemen categoryRatingChart ada di DOM
            if (document.querySelector("#categoryRatingChart")) {
                const categoryRatingOptions = {
                    series: [{
                        name: 'میانگین امتیاز',
                        data: <?php echo json_encode($ratingAnalytics['byCategory']['data'] ?? [], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'bar',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            horizontal: true,
                            dataLabels: {
                                position: 'bottom'
                            }
                        }
                    },
                    dataLabels: {
                        enabled: true,
                        formatter: function (val) {
                            return val.toFixed(1);
                        }
                    },
                    xaxis: {
                        categories: <?php echo json_encode($ratingAnalytics['byCategory']['labels'] ?? [], 15, 512) ?>,
                    },
                    colors: ['#4e73df'],
                    title: {
                        text: 'میانگین امتیازات بر اساس دسته‌بندی',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#categoryRatingChart", categoryRatingOptions);
            }

            // Verifikasi apakah elemen ratingTrendsChart ada di DOM
            if (document.querySelector("#ratingTrendsChart")) {
                const ratingTrendsOptions = {
                    series: [{
                        name: 'میانگین امتیاز',
                        data: <?php echo json_encode($ratingAnalytics['trends']['data'] ?? [], 15, 512) ?>
                    }],
                    chart: {
                        height: 350,
                        type: 'line',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    stroke: {
                        width: 3,
                        curve: 'smooth'
                    },
                    dataLabels: {
                        enabled: true,
                        formatter: function (val) {
                            return val.toFixed(1);
                        }
                    },
                    xaxis: {
                        categories: <?php echo json_encode($ratingAnalytics['trends']['labels'] ?? [], 15, 512) ?>,
                    },
                    yaxis: {
                        min: 0,
                        max: 5,
                    },
                    colors: ['#f6c23e'],
                    title: {
                        text: 'روند امتیازات در طول زمان',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#ratingTrendsChart", ratingTrendsOptions);
            }
        }

        function initGeoAnalysisCharts() {
            // Implementasi fungsi untuk inisialisasi chart geografis

            // Definisi fungsi rendering chart provinsi
            window.renderProvincesChart = function() {
                // Sample data for provinces - in a real app, this would come from the server
                const provincesData = <?php echo json_encode($geographicData['provinces']['data'] ?? [], 15, 512) ?>;
                const provinceLabels = <?php echo json_encode($geographicData['provinces']['labels'] ?? [], 15, 512) ?>;

                const options = {
                    series: [{
                        name: 'تعداد مکان‌ها',
                        data: provincesData
                    }],
                    chart: {
                        type: 'bar',
                        height: 350,
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                        dir: 'rtl',
                        toolbar: {
                            show: false
                        }
                    },
                    plotOptions: {
                        bar: {
                            horizontal: true,
                            barHeight: '70%',
                            dataLabels: {
                                position: 'bottom'
                            }
                        }
                    },
                    colors: ['#33b2df', '#546E7A', '#d4526e', '#13d8aa', '#A5978B'],
                    dataLabels: {
                        enabled: true,
                        textAnchor: 'start',
                        formatter: function(val) {
                            return val;
                        },
                        offsetX: 0
                    },
                    xaxis: {
                        categories: provinceLabels,
                    },
                    title: {
                        text: 'توزیع مکان‌ها بر اساس استان',
                        align: 'center'
                    }
                };

                // Check if element exists before rendering using safe wrapper
                if (document.querySelector("#provinces-chart")) {
                    createChart("#provinces-chart", options);
                }

                // Populate provinces list if the element exists
                if (document.querySelector("#provinces-top .list-group")) {
                    let listHTML = '';

                    for (let i = 0; i < Math.min(5, provinceLabels.length); i++) {
                        const total = provincesData.reduce((a, b) => a + b, 0);
                        const percent = total > 0 ? (provincesData[i] / total * 100).toFixed(1) : 0;

                        listHTML += `
                            <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge badge-primary badge-pill mr-2">${i + 1}</span>
                                    ${provinceLabels[i]}
                                </div>
                                <div>
                                    <span class="badge badge-light badge-pill">${percent}%</span>
                                </div>
                            </a>
                        `;
                    }

                    document.querySelector("#provinces-top .list-group").innerHTML = listHTML;
                }
            }

            // Definisi fungsi rendering chart kota
            window.renderCitiesChart = function() {
                // Sample data for cities - in a real app, this would come from the server
                const citiesData = <?php echo json_encode($geographicData['cities']['data'] ?? [], 15, 512) ?>;
                const cityLabels = <?php echo json_encode($geographicData['cities']['labels'] ?? [], 15, 512) ?>;

                const options = {
                    series: [{
                        name: 'تعداد مکان‌ها',
                        data: citiesData
                    }],
                    chart: {
                        type: 'bar',
                        height: 350,
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                        dir: 'rtl',
                        toolbar: {
                            show: false
                        }
                    },
                    plotOptions: {
                        bar: {
                            horizontal: true,
                            barHeight: '70%',
                            distributed: true
                        }
                    },
                    colors: ['#33b2df', '#546E7A', '#d4526e', '#13d8aa', '#A5978B'],
                    dataLabels: {
                        enabled: true,
                        textAnchor: 'start',
                        formatter: function(val) {
                            return val;
                        },
                        offsetX: 0
                    },
                    xaxis: {
                        categories: cityLabels
                    },
                    title: {
                        text: 'توزیع مکان‌ها بر اساس شهر (15 شهر برتر)',
                        align: 'center'
                    }
                };

                // Check if element exists before rendering using safe wrapper
                if (document.querySelector("#cities-chart")) {
                    createChart("#cities-chart", options);
                }

                // Populate cities list if the element exists
                if (document.querySelector("#cities-top .list-group")) {
                    let listHTML = '';

                    for (let i = 0; i < Math.min(5, cityLabels.length); i++) {
                        const total = citiesData.reduce((a, b) => a + b, 0);
                        const percent = total > 0 ? (citiesData[i] / total * 100).toFixed(1) : 0;

                        listHTML += `
                            <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge badge-primary badge-pill mr-2">${i + 1}</span>
                                    ${cityLabels[i]}
                                </div>
                                <div>
                                    <span class="badge badge-light badge-pill">${percent}%</span>
                                </div>
                            </a>
                        `;
                    }

                    document.querySelector("#cities-top .list-group").innerHTML = listHTML;
                }
            }

            // Initialize geography charts
            if (document.querySelector("[data-geography-chart].active")) {
                const activeChartType = document.querySelector("[data-geography-chart].active").getAttribute('data-geography-chart');

                if (activeChartType === 'provinces') {
                    renderProvincesChart();
                    document.querySelectorAll(`[data-chart-type="provinces"]`).forEach(container => {
                        container.classList.remove('d-none');
                    });
                } else if (activeChartType === 'cities') {
                    renderCitiesChart();
                    document.querySelectorAll(`[data-chart-type="cities"]`).forEach(container => {
                        container.classList.remove('d-none');
                    });
                } else if (activeChartType === 'heatmap') {
                    renderIranHeatmap();
                    document.querySelectorAll(`[data-chart-type="heatmap"]`).forEach(container => {
                        container.classList.remove('d-none');
                    });
                }
            } else {
                // Default to provinces view
                renderProvincesChart();
                document.querySelectorAll(`[data-chart-type="provinces"]`).forEach(container => {
                    container.classList.remove('d-none');
                });

                // Set the provinces button as active
                const provincesButton = document.querySelector('[data-geography-chart="provinces"]');
                if (provincesButton) {
                    provincesButton.classList.add('active');
                }
            }

            // Add event listeners for switching between chart types
            document.querySelectorAll('[data-geography-chart]').forEach(button => {
                button.addEventListener('click', function() {
                    // Remove active class from all buttons
                    document.querySelectorAll('[data-geography-chart]').forEach(btn => {
                        btn.classList.remove('active');
                    });

                    // Add active class to clicked button
                    this.classList.add('active');

                    // Hide all chart containers
                    document.querySelectorAll('.geography-chart').forEach(container => {
                        container.classList.add('d-none');
                    });

                    // Show the selected chart containers
                    const chartType = this.getAttribute('data-geography-chart');
                    document.querySelectorAll(`[data-chart-type="${chartType}"]`).forEach(container => {
                        container.classList.remove('d-none');
                    });

                    // Initialize the appropriate chart
                    if (chartType === 'provinces') {
                        renderProvincesChart();
                    } else if (chartType === 'cities') {
                        renderCitiesChart();
                    } else if (chartType === 'heatmap') {
                        renderIranHeatmap();
                    }
                });
            });
        }

        function initTrendsAnalysisCharts() {
            // Implementación de las gráficas de tendencias
            // Verifikasi apakah elemen weeklyGrowthChart ada di DOM
            if (document.querySelector("#weeklyGrowthChart")) {
                // Extract weekly data
                const weeklyLabels = [];
                const weeklyData = [];
                const weeklyGrowth = [];

                <?php $__currentLoopData = $trendAnalysis['weekly'] ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $week): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    weeklyLabels.push('<?php echo e($week['week']); ?>');
                    weeklyData.push(<?php echo e($week['count']); ?>);
                    weeklyGrowth.push(<?php echo e($week['growth']); ?>);
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                // Initialize Weekly Growth Chart
                const weeklyGrowthOptions = {
                    series: [{
                        name: 'تعداد مکان‌ها',
                        type: 'column',
                        data: weeklyData
                    }, {
                        name: 'درصد رشد',
                        type: 'line',
                        data: weeklyGrowth
                    }],
                    chart: {
                        height: 350,
                        type: 'line',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    stroke: {
                        width: [0, 3]
                    },
                    dataLabels: {
                        enabled: true,
                        enabledOnSeries: [1],
                        formatter: function (val) {
                            return val + '%';
                        }
                    },
                    labels: weeklyLabels,
                    colors: ['#4e73df', '#1cc88a'],
                    title: {
                        text: 'روند رشد هفتگی مکان‌ها',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#weeklyGrowthChart", weeklyGrowthOptions);
            }

            // Verifikasi apakah elemen categoriesGrowthChart ada di DOM
            if (document.querySelector("#categoriesGrowthChart")) {
                // Extract categories growth data
                const categoryLabels = [];
                const categoryGrowths = [];
                const categoryColors = [];

                <?php $__currentLoopData = $trendAnalysis['categories'] ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    categoryLabels.push('<?php echo e($category['category']); ?>');
                    categoryGrowths.push(<?php echo e($category['growth']); ?>);
                    categoryColors.push('<?php echo e($category['growth'] >= 0 ? '#1cc88a' : '#e74a3b'); ?>');
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                // Initialize Categories Growth Chart
                const categoriesGrowthOptions = {
                    series: [{
                        name: 'درصد رشد',
                        data: categoryGrowths
                    }],
                    chart: {
                        height: 350,
                        type: 'bar',
                        fontFamily: 'IRANSans, tahoma, sans-serif',
                    },
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            horizontal: true,
                            distributed: true,
                        }
                    },
                    colors: categoryColors,
                    dataLabels: {
                        enabled: true,
                        formatter: function (val) {
                            return val + '%';
                        }
                    },
                    legend: {
                        show: false
                    },
                    xaxis: {
                        categories: categoryLabels,
                    },
                    title: {
                        text: 'درصد رشد دسته‌بندی‌ها در ماه اخیر',
                        align: 'center',
                        style: {
                            fontSize: '14px',
                            fontWeight: 'bold',
                        }
                    }
                };

                // Use safe wrapper instead of direct initialization
                createChart("#categoriesGrowthChart", categoriesGrowthOptions);
            }
        }

        // تابع شروع بروزرسانی داده‌های لحظه‌ای
        function startRealtimeUpdates() {
            console.log('Starting realtime updates...');

            // بروزرسانی فوری
            updateRealtimeData();

            // بروزرسانی هر 30 ثانیه
            if (window.realtimeInterval) {
                clearInterval(window.realtimeInterval);
            }

            window.realtimeInterval = setInterval(updateRealtimeData, 30000);
        }

        // تابع بروزرسانی داده‌های لحظه‌ای
        function updateRealtimeData() {
            fetch('<?php echo e(route("admin.analytics.realtime")); ?>')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('Realtime data updated:', data.data);

                        // بروزرسانی آمار فوری
                        updateQuickStats(data.data.quick_stats);

                        // بروزرسانی نمودار لحظه‌ای
                        updateRealtimeChart(data.data.realtime);

                        // بروزرسانی timestamp
                        updateLastUpdateTime(data.data.timestamp);
                    }
                })
                .catch(error => {
                    console.error('Error fetching realtime data:', error);
                });
        }

        // بروزرسانی آمار فوری
        function updateQuickStats(stats) {
            // بروزرسانی کاربران آنلاین
            const onlineUsersElement = document.querySelector('[data-realtime="active_users"]');
            if (onlineUsersElement) {
                onlineUsersElement.textContent = stats.active_users_online;
            }

            // بروزرسانی مکان‌های امروز
            const todayLocationsElement = document.querySelector('[data-realtime="today_locations"]');
            if (todayLocationsElement) {
                todayLocationsElement.textContent = stats.today_locations;
            }

            // بروزرسانی ساعت پیک
            const peakHourElement = document.querySelector('[data-realtime="peak_hour"]');
            if (peakHourElement) {
                peakHourElement.textContent = stats.peak_hour_today;
            }
        }

        // بروزرسانی نمودار لحظه‌ای
        function updateRealtimeChart(realtimeData) {
            if (window.realtimeChart) {
                window.realtimeChart.updateSeries([{
                    name: 'فعالیت ساعتی',
                    data: realtimeData.data
                }]);
            }
        }

        // بروزرسانی زمان آخرین بروزرسانی
        function updateLastUpdateTime(timestamp) {
            const lastUpdateElement = document.querySelector('[data-realtime="last_update"]');
            if (lastUpdateElement) {
                const date = new Date(timestamp);
                const persianTime = date.toLocaleTimeString('fa-IR');
                lastUpdateElement.textContent = persianTime;
            }
        }

        // توقف بروزرسانی‌های لحظه‌ای
        function stopRealtimeUpdates() {
            if (window.realtimeInterval) {
                clearInterval(window.realtimeInterval);
                window.realtimeInterval = null;
                console.log('Realtime updates stopped');
            }
        }

        // پاک‌سازی در هنگام خروج از صفحه
        window.addEventListener('beforeunload', function() {
            stopRealtimeUpdates();
        });

        // توابع جدید برای صفحه جغرافیایی
        function refreshGeoData() {
            console.log('Refreshing geographic data...');
            // نمایش loading
            showGeoLoading();

            // درخواست بروزرسانی داده‌ها
            fetch('<?php echo e(route("admin.analytics.refresh")); ?>')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // بروزرسانی داده‌های جغرافیایی
                        window.geographicData = data.data.geographicData;

                        // بروزرسانی نمودارها
                        const activeChartType = document.querySelector('[data-geography-chart].active').getAttribute('data-geography-chart');
                        initGeographyCharts(activeChartType);

                        // نمایش پیام موفقیت
                        showNotification('داده‌های جغرافیایی با موفقیت بروزرسانی شدند', 'success');
                    }
                })
                .catch(error => {
                    console.error('Error refreshing geo data:', error);
                    showNotification('خطا در بروزرسانی داده‌ها', 'error');
                })
                .finally(() => {
                    hideGeoLoading();
                });
        }

        function exportGeoData(format) {
            console.log('Exporting geographic data as:', format);

            const activeChartType = document.querySelector('[data-geography-chart].active').getAttribute('data-geography-chart');
            const filters = getGeoFilters();

            const params = new URLSearchParams({
                type: activeChartType,
                format: format,
                ...filters
            });

            window.open(`<?php echo e(route("admin.analytics.export")); ?>?${params.toString()}`, '_blank');
            showNotification(`در حال تهیه فایل ${format.toUpperCase()}...`, 'info');
        }

        function showGeoFilters() {
            // نمایش modal فیلترهای پیشرفته
            console.log('Showing advanced geo filters...');
            // اینجا می‌توان modal پیشرفته‌تری اضافه کرد
        }

        function showGeoComparison() {
            // نمایش مقایسه مناطق
            console.log('Showing geographic comparison...');
            // اینجا می‌توان صفحه مقایسه اضافه کرد
        }

        function toggleChartType(region, chartType) {
            console.log('Toggling chart type:', region, chartType);

            // بروزرسانی دکمه‌های فعال
            const buttons = document.querySelectorAll(`[data-chart-type="${region}"] .chart-actions .btn`);
            buttons.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            // بروزرسانی نمودار
            if (region === 'provinces') {
                renderProvincesChart(chartType);
            } else if (region === 'cities') {
                renderCitiesChart(chartType);
            }
        }

        function setHeatmapMode(mode) {
            console.log('Setting heatmap mode:', mode);

            // بروزرسانی دکمه‌های فعال
            const buttons = document.querySelectorAll('.heatmap-controls .btn-group .btn');
            buttons.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            // بروزرسانی نقشه حرارتی
            updateHeatmapMode(mode);
        }

        function zoomToProvince() {
            console.log('Zooming to province...');
            // نمایش لیست استان‌ها برای انتخاب
            if (window.iranHeatmap) {
                // اینجا می‌توان dropdown استان‌ها اضافه کرد
                showNotification('لطفاً استان مورد نظر را انتخاب کنید', 'info');
            }
        }

        function resetMapView() {
            console.log('Resetting map view...');
            if (window.iranHeatmap) {
                window.iranHeatmap.setView([32.4279, 53.6880], 6);
                showNotification('نمای نقشه بازنشانی شد', 'success');
            }
        }

        function toggleMapLayers() {
            console.log('Toggling map layers...');
            // اینجا می‌توان لایه‌های مختلف نقشه را تغییر داد
            showNotification('لایه‌های نقشه تغییر کرد', 'info');
        }

        function resetGeoFilters() {
            console.log('Resetting geo filters...');

            // بازنشانی فیلترها
            document.getElementById('geo-date-range').value = '30';
            document.getElementById('geo-analysis-type').value = 'locations';
            document.getElementById('geo-category-filter').value = 'all';
            document.getElementById('geo-min-count').value = '1';

            // اعمال فیلترهای پیش‌فرض
            const activeChartType = document.querySelector('[data-geography-chart].active').getAttribute('data-geography-chart');
            applyGeoFilters('30', 'locations', activeChartType);

            showNotification('فیلترها بازنشانی شدند', 'success');
        }

        function refreshInsights() {
            console.log('Refreshing insights...');

            const insightsContainer = document.getElementById('geo-insights');
            insightsContainer.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> در حال بروزرسانی...</div>';

            setTimeout(() => {
                // شبیه‌سازی بروزرسانی بینش‌ها
                location.reload();
            }, 1000);
        }

        function exportInsights() {
            console.log('Exporting insights...');
            showNotification('در حال تهیه گزارش بینش‌ها...', 'info');
        }

        function getGeoFilters() {
            return {
                dateRange: document.getElementById('geo-date-range').value,
                analysisType: document.getElementById('geo-analysis-type').value,
                category: document.getElementById('geo-category-filter').value,
                minCount: document.getElementById('geo-min-count').value
            };
        }

        function showGeoLoading() {
            // نمایش loading در تمام بخش‌های جغرافیایی
            const containers = document.querySelectorAll('.geo-chart-card, .geo-ranking-card, .geo-heatmap-card');
            containers.forEach(container => {
                const body = container.querySelector('.chart-body, .ranking-body, .heatmap-body');
                if (body) {
                    body.innerHTML = '<div class="text-center p-4"><i class="fas fa-spinner fa-spin fa-2x text-primary"></i><br><small class="text-muted mt-2">در حال بارگذاری...</small></div>';
                }
            });
        }

        function hideGeoLoading() {
            // مخفی کردن loading (نمودارها دوباره رسم می‌شوند)
            console.log('Loading hidden, charts will be redrawn');
        }

        function updateHeatmapMode(mode) {
            if (!window.iranHeatmap || !window.heatLayer) return;

            // تغییر تنظیمات نقشه حرارتی بر اساس حالت
            let options = {};

            switch(mode) {
                case 'density':
                    options = { radius: 25, blur: 15, maxZoom: 10 };
                    break;
                case 'activity':
                    options = { radius: 30, blur: 20, maxZoom: 8 };
                    break;
                case 'growth':
                    options = { radius: 20, blur: 10, maxZoom: 12 };
                    break;
            }

            // بروزرسانی لایه حرارتی
            if (window.heatLayer) {
                window.iranHeatmap.removeLayer(window.heatLayer);
                // اینجا باید لایه جدید با تنظیمات جدید ایجاد شود
                // window.heatLayer = L.heatLayer(heatData, options).addTo(window.iranHeatmap);
            }
        }

        function showNotification(message, type = 'info') {
            // نمایش notification ساده
            const alertClass = type === 'success' ? 'alert-success' :
                             type === 'error' ? 'alert-danger' : 'alert-info';

            const notification = document.createElement('div');
            notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
            notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;

            document.body.appendChild(notification);

            // حذف خودکار بعد از 3 ثانیه
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 3000);
        }
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/aluirani/public_html/aludubai.ir/resources/views/admin/analytics/index.blade.php ENDPATH**/ ?>