<div class="tab-pane fade" id="categoryAnalysis" role="tabpanel">
    <!-- Enhanced Header Section -->
    <div class="category-header-section mb-4">
        <div class="row align-items-center">
            <div class="col-md-6">
                <div class="category-title-wrapper">
                    <h4 class="category-main-title">
                        <i class="fas fa-layer-group text-primary me-2"></i>
                        تحلیل دسته‌بندی‌ها
                    </h4>
                    <p class="category-subtitle text-muted mb-0">
                        بررسی توزیع و عملکرد دسته‌بندی‌های مختلف مکان‌ها
                    </p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="category-controls d-flex justify-content-end">
                    <div class="btn-group category-toggle-group me-2" role="group">
                        <button type="button" class="btn btn-outline-primary active" data-category-chart="distribution">
                            <i class="fas fa-chart-pie me-1"></i>
                            توزیع مکان‌ها
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-category-chart="growth">
                            <i class="fas fa-chart-bar me-1"></i>
                            رشد دسته‌ها
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-category-chart="comparison">
                            <i class="fas fa-balance-scale me-1"></i>
                            مقایسه
                        </button>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-cog me-1"></i>
                            تنظیمات
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="refreshCategoryData()">
                                <i class="fas fa-sync-alt me-2"></i>بروزرسانی داده‌ها
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportCategoryData('excel')">
                                <i class="fas fa-file-excel me-2"></i>خروجی Excel
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportCategoryData('pdf')">
                                <i class="fas fa-file-pdf me-2"></i>خروجی PDF
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="showCategorySettings()">
                                <i class="fas fa-sliders-h me-2"></i>تنظیمات نمایش
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Stats Overview -->
    <div class="category-stats-overview mb-4">
        <div class="row">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon bg-primary">
                        <i class="fas fa-layer-group"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ count($categoryAnalytics['distribution']['labels']) }}</div>
                        <div class="stat-label">کل دسته‌بندی‌ها</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon bg-success">
                        <i class="fas fa-map-marker-alt"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ array_sum($categoryAnalytics['distribution']['data']) }}</div>
                        <div class="stat-label">کل مکان‌ها</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon bg-warning">
                        <i class="fas fa-crown"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ $categoryAnalytics['distribution']['labels'][0] ?? 'N/A' }}</div>
                        <div class="stat-label">دسته برتر</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon bg-info">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-content">
                        @php
                            $avgGrowth = count($categoryAnalytics['growth']['data']) > 0 ?
                                round(array_sum($categoryAnalytics['growth']['data']) / count($categoryAnalytics['growth']['data']), 1) : 0;
                        @endphp
                        <div class="stat-value">{{ $avgGrowth > 0 ? '+' : '' }}{{ $avgGrowth }}%</div>
                        <div class="stat-label">میانگین رشد</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Charts Section -->
    <div class="row">
        <!-- Category Distribution Chart -->
        <div class="col-lg-8 category-chart" id="categoryDistribution">
            <div class="card category-chart-card">
                <div class="card-header bg-gradient-primary text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-chart-pie me-2"></i>
                            نمودار توزیع دسته‌بندی‌ها
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('distribution')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('categoryDistributionChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('categoryDistributionChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="categoryDistributionChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Category Distribution Statistics -->
        <div class="col-lg-4 category-chart" id="categoryDistributionStats">
            <div class="card category-stats-card">
                <div class="card-header bg-gradient-info text-white">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-list-alt me-2"></i>
                        آمار توزیع دسته‌بندی‌ها
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="category-stats-list">
                        @foreach ($categoryAnalytics['distribution']['labels'] as $index => $category)
                            @php
                                $total = array_sum($categoryAnalytics['distribution']['data']);
                                $percent = $total > 0 ? round(($categoryAnalytics['distribution']['data'][$index] / $total) * 100, 1) : 0;
                                $count = $categoryAnalytics['distribution']['data'][$index];
                                $color = $categoryAnalytics['distribution']['colors'][$index] ?? '#667eea';
                            @endphp
                            <div class="category-stat-item">
                                <div class="d-flex align-items-center justify-content-between p-3">
                                    <div class="d-flex align-items-center">
                                        <div class="category-color-indicator" style="background-color: {{ $color }}"></div>
                                        <div class="category-info">
                                            <div class="category-name">{{ $category }}</div>
                                            <div class="category-rank">رتبه {{ $index + 1 }}</div>
                                        </div>
                                    </div>
                                    <div class="category-metrics text-end">
                                        <div class="category-count">{{ number_format($count) }}</div>
                                        <div class="category-percentage">{{ $percent }}%</div>
                                    </div>
                                </div>
                                <div class="category-progress-bar">
                                    <div class="progress" style="height: 4px;">
                                        <div class="progress-bar"
                                             style="width: {{ $percent }}%; background-color: {{ $color }}"
                                             role="progressbar"
                                             aria-valuenow="{{ $percent }}"
                                             aria-valuemin="0"
                                             aria-valuemax="100">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <!-- Summary Footer -->
                    <div class="category-stats-summary p-3 bg-light">
                        <div class="row text-center">
                            <div class="col-4">
                                <div class="summary-metric">
                                    <div class="metric-value text-primary">{{ number_format($total) }}</div>
                                    <div class="metric-label">کل مکان‌ها</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="summary-metric">
                                    <div class="metric-value text-success">{{ count($categoryAnalytics['distribution']['labels']) }}</div>
                                    <div class="metric-label">دسته‌بندی‌ها</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="summary-metric">
                                    @php
                                        $avgPerCategory = count($categoryAnalytics['distribution']['labels']) > 0 ?
                                            round($total / count($categoryAnalytics['distribution']['labels'])) : 0;
                                    @endphp
                                    <div class="metric-value text-info">{{ number_format($avgPerCategory) }}</div>
                                    <div class="metric-label">میانگین</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Category Growth Chart (hidden initially) -->
        <div class="col-12 category-chart" id="categoryGrowth" style="display: none;">
            <div class="card category-chart-card">
                <div class="card-header bg-gradient-success text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-chart-bar me-2"></i>
                            نمودار رشد دسته‌بندی‌ها
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('growth')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('categoryGrowthChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('categoryGrowthChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-success" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="categoryGrowthChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Category Comparison Chart (hidden initially) -->
        <div class="col-12 category-chart" id="categoryComparison" style="display: none;">
            <div class="card category-chart-card">
                <div class="card-header bg-gradient-warning text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-balance-scale me-2"></i>
                            مقایسه عملکرد دسته‌بندی‌ها
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('comparison')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('categoryComparisonChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('categoryComparisonChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-warning" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="categoryComparisonChart"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Category Status Cards -->
    <div class="category-status-section mt-4">
        <div class="card category-status-card">
            <div class="card-header bg-gradient-dark text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-chart-area me-2"></i>
                        وضعیت تفصیلی دسته‌بندی‌ها
                    </h5>
                    <div class="status-actions">
                        <button class="btn btn-sm btn-outline-light" onclick="sortCategories('count')" title="مرتب‌سازی بر اساس تعداد">
                            <i class="fas fa-sort-amount-down"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-light" onclick="sortCategories('growth')" title="مرتب‌سازی بر اساس رشد">
                            <i class="fas fa-sort-numeric-down"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row category-cards-grid">
                    @foreach ($categoryAnalytics['distribution']['labels'] as $index => $category)
                        @php
                            $count = $categoryAnalytics['distribution']['data'][$index];
                            $growth = $categoryAnalytics['growth']['data'][$index] ?? 0;
                            $growthClass = $growth >= 0 ? 'positive' : 'negative';
                            $growthIcon = $growth >= 0 ? 'arrow-up' : 'arrow-down';
                            $color = $categoryAnalytics['distribution']['colors'][$index] ?? '#667eea';
                            $total = array_sum($categoryAnalytics['distribution']['data']);
                            $percent = $total > 0 ? round(($count / $total) * 100, 1) : 0;
                            $maxCount = max($categoryAnalytics['distribution']['data']);
                            $relativeWidth = $maxCount > 0 ? ($count / $maxCount) * 100 : 0;
                        @endphp
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="category-status-item {{ $growth >= 0 ? 'growing' : 'declining' }}">
                                <div class="category-header">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="category-title-section">
                                            <div class="category-icon" style="background-color: {{ $color }}">
                                                <i class="fas fa-layer-group"></i>
                                            </div>
                                            <div class="category-details">
                                                <h6 class="category-title">{{ $category }}</h6>
                                                <div class="category-badge">
                                                    <span class="badge bg-primary">رتبه {{ $index + 1 }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="category-growth-indicator">
                                            <span class="growth-badge {{ $growthClass }}">
                                                <i class="fas fa-{{ $growthIcon }}"></i>
                                                {{ abs($growth) }}%
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="category-metrics">
                                    <div class="row">
                                        <div class="col-6">
                                            <div class="metric-item">
                                                <div class="metric-value">{{ number_format($count) }}</div>
                                                <div class="metric-label">تعداد مکان</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="metric-item">
                                                <div class="metric-value">{{ $percent }}%</div>
                                                <div class="metric-label">سهم کل</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="category-progress-section">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="progress-label">نسبت به بیشترین</span>
                                        <span class="progress-percentage">{{ round($relativeWidth) }}%</span>
                                    </div>
                                    <div class="progress category-progress" style="height: 8px;">
                                        <div class="progress-bar"
                                             style="width: {{ $relativeWidth }}%; background: linear-gradient(90deg, {{ $color }}, {{ $color }}aa)"
                                             role="progressbar"
                                             aria-valuenow="{{ $relativeWidth }}"
                                             aria-valuemin="0"
                                             aria-valuemax="100">
                                        </div>
                                    </div>
                                </div>

                                <div class="category-insights">
                                    @if($growth > 10)
                                        <div class="insight-item success">
                                            <i class="fas fa-rocket me-1"></i>
                                            رشد قابل توجه
                                        </div>
                                    @elseif($growth > 0)
                                        <div class="insight-item info">
                                            <i class="fas fa-chart-line me-1"></i>
                                            رشد مثبت
                                        </div>
                                    @elseif($growth < -10)
                                        <div class="insight-item danger">
                                            <i class="fas fa-exclamation-triangle me-1"></i>
                                            نیاز به توجه
                                        </div>
                                    @else
                                        <div class="insight-item warning">
                                            <i class="fas fa-minus me-1"></i>
                                            وضعیت پایدار
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Enhanced Category Distribution Chart
        const categoryDistOptions = {
            series: @json($categoryAnalytics['distribution']['data']),
            chart: {
                height: 450,
                type: 'donut',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800,
                    animateGradually: {
                        enabled: true,
                        delay: 150
                    },
                    dynamicAnimation: {
                        enabled: true,
                        speed: 350
                    }
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: false,
                        zoom: false,
                        zoomin: false,
                        zoomout: false,
                        pan: false,
                        reset: false
                    }
                },
                background: 'transparent'
            },
            labels: @json($categoryAnalytics['distribution']['labels']),
            colors: @json($categoryAnalytics['distribution']['colors']),
            plotOptions: {
                pie: {
                    startAngle: -90,
                    endAngle: 270,
                    expandOnClick: true,
                    donut: {
                        size: '45%',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                fontSize: '14px',
                                fontWeight: 600,
                                color: '#373d3f'
                            },
                            value: {
                                show: true,
                                fontSize: '16px',
                                fontWeight: 700,
                                color: '#667eea',
                                formatter: function (val) {
                                    return parseInt(val) + ' مکان';
                                }
                            },
                            total: {
                                show: true,
                                showAlways: false,
                                label: 'کل مکان‌ها',
                                fontSize: '14px',
                                fontWeight: 600,
                                color: '#373d3f',
                                formatter: function (w) {
                                    return w.globals.seriesTotals.reduce((a, b) => {
                                        return a + b;
                                    }, 0) + ' مکان';
                                }
                            }
                        }
                    }
                }
            },
            stroke: {
                show: true,
                width: 3,
                colors: ['#fff']
            },
            responsive: [{
                breakpoint: 768,
                options: {
                    chart: {
                        height: 350
                    },
                    legend: {
                        position: 'bottom',
                        fontSize: '11px'
                    }
                }
            }],
            dataLabels: {
                enabled: true,
                formatter: function (val, opt) {
                    return Math.round(val) + '%';
                },
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ['#fff']
                },
                dropShadow: {
                    enabled: true,
                    top: 1,
                    left: 1,
                    blur: 1,
                    color: '#000',
                    opacity: 0.45
                }
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function(val, opts) {
                        return val + ' مکان (' + opts.w.globals.seriesPercent[opts.seriesIndex][0].toFixed(1) + '%)';
                    }
                }
            },
            legend: {
                position: 'right',
                offsetY: 0,
                height: 300,
                fontSize: '12px',
                fontWeight: 500,
                markers: {
                    width: 12,
                    height: 12,
                    radius: 6
                },
                itemMargin: {
                    horizontal: 5,
                    vertical: 8
                }
            }
        };

        const categoryDistChart = new ApexCharts(document.querySelector("#categoryDistributionChart"), categoryDistOptions);
        categoryDistChart.render();

        // Enhanced Category Growth Chart
        const categoryGrowthOptions = {
            series: [{
                name: 'درصد رشد',
                data: @json($categoryAnalytics['growth']['data'])
            }],
            chart: {
                height: 400,
                type: 'bar',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800,
                    animateGradually: {
                        enabled: true,
                        delay: 150
                    }
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: false,
                        zoom: false,
                        zoomin: false,
                        zoomout: false,
                        pan: false,
                        reset: false
                    }
                },
                background: 'transparent'
            },
            plotOptions: {
                bar: {
                    borderRadius: 8,
                    columnWidth: '60%',
                    dataLabels: {
                        position: 'top',
                    },
                    colors: {
                        ranges: [{
                            from: -100,
                            to: 0,
                            color: '#dc3545'
                        }, {
                            from: 0,
                            to: 100,
                            color: '#28a745'
                        }]
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: undefined,
                    inverseColors: false,
                    opacityFrom: 0.85,
                    opacityTo: 0.55,
                    stops: [50, 0, 100]
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function (val) {
                    return val + '%';
                },
                offsetY: -20,
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ["#304758"]
                }
            },
            xaxis: {
                categories: @json($categoryAnalytics['growth']['labels']),
                labels: {
                    rotate: -45,
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                axisBorder: {
                    show: true,
                    color: '#e0e6ed'
                },
                axisTicks: {
                    show: true,
                    color: '#e0e6ed'
                }
            },
            yaxis: {
                labels: {
                    formatter: function (val) {
                        return val + '%';
                    },
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                title: {
                    text: 'درصد رشد',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                }
            },
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3,
                xaxis: {
                    lines: {
                        show: true
                    }
                },
                yaxis: {
                    lines: {
                        show: true
                    }
                }
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val) {
                        return val + '% رشد';
                    }
                }
            }
        };

        const categoryGrowthChart = new ApexCharts(document.querySelector("#categoryGrowthChart"), categoryGrowthOptions);
        categoryGrowthChart.render();

        // Enhanced Category Comparison Chart
        const categoryComparisonOptions = {
            series: [{
                name: 'تعداد مکان‌ها',
                type: 'column',
                data: @json($categoryAnalytics['distribution']['data'])
            }, {
                name: 'درصد رشد',
                type: 'line',
                data: @json($categoryAnalytics['growth']['data'])
            }],
            chart: {
                height: 400,
                type: 'line',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: true,
                        zoom: true,
                        zoomin: true,
                        zoomout: true,
                        pan: true,
                        reset: true
                    }
                },
                background: 'transparent'
            },
            stroke: {
                width: [0, 4],
                curve: 'smooth'
            },
            fill: {
                type: ['gradient', 'solid'],
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: ['#667eea'],
                    inverseColors: false,
                    opacityFrom: 0.85,
                    opacityTo: 0.55,
                    stops: [50, 0, 100]
                }
            },
            dataLabels: {
                enabled: true,
                enabledOnSeries: [1],
                formatter: function (val) {
                    return val + '%';
                },
                style: {
                    fontSize: '11px',
                    fontWeight: 'bold',
                    colors: ['#304758']
                }
            },
            labels: @json($categoryAnalytics['distribution']['labels']),
            xaxis: {
                type: 'category',
                labels: {
                    rotate: -45,
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                }
            },
            yaxis: [{
                title: {
                    text: 'تعداد مکان‌ها',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                },
                labels: {
                    formatter: function (val) {
                        return val.toFixed(0);
                    },
                    style: {
                        fontSize: '11px',
                        colors: '#6c757d'
                    }
                }
            }, {
                opposite: true,
                title: {
                    text: 'درصد رشد',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                },
                labels: {
                    formatter: function (val) {
                        return val.toFixed(0) + '%';
                    },
                    style: {
                        fontSize: '11px',
                        colors: '#6c757d'
                    }
                }
            }],
            colors: ['#667eea', '#28a745'],
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3
            },
            legend: {
                position: 'top',
                horizontalAlign: 'center',
                fontSize: '12px',
                fontWeight: 500,
                markers: {
                    width: 12,
                    height: 12,
                    radius: 6
                }
            },
            tooltip: {
                shared: true,
                intersect: false,
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val, { seriesIndex }) {
                        if (seriesIndex === 0) {
                            return val + ' مکان';
                        } else {
                            return val + '% رشد';
                        }
                    }
                }
            }
        };

        const categoryComparisonChart = new ApexCharts(document.querySelector("#categoryComparisonChart"), categoryComparisonOptions);
        categoryComparisonChart.render();

        // Store chart instances for later use
        window.categoryCharts = {
            distribution: categoryDistChart,
            growth: categoryGrowthChart,
            comparison: categoryComparisonChart
        };

        // Enhanced Category chart toggle functionality
        const categoryChartButtons = document.querySelectorAll('[data-category-chart]');
        const categoryCharts = document.querySelectorAll('.category-chart');

        categoryChartButtons.forEach(button => {
            button.addEventListener('click', function() {
                // Add loading animation
                showCategoryLoading();

                // Remove active class from all buttons
                categoryChartButtons.forEach(btn => btn.classList.remove('active'));

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

                // Hide all charts with animation
                categoryCharts.forEach(chart => {
                    chart.style.opacity = '0';
                    setTimeout(() => {
                        chart.style.display = 'none';
                    }, 300);
                });

                // Show selected chart with animation
                const selectedChart = this.getAttribute('data-category-chart');
                setTimeout(() => {
                    if (selectedChart === 'distribution') {
                        document.getElementById('categoryDistribution').style.display = 'block';
                        document.getElementById('categoryDistributionStats').style.display = 'block';
                        setTimeout(() => {
                            document.getElementById('categoryDistribution').style.opacity = '1';
                            document.getElementById('categoryDistributionStats').style.opacity = '1';
                        }, 50);
                    } else {
                        document.getElementById(`category${selectedChart.charAt(0).toUpperCase() + selectedChart.slice(1)}`).style.display = 'block';
                        setTimeout(() => {
                            document.getElementById(`category${selectedChart.charAt(0).toUpperCase() + selectedChart.slice(1)}`).style.opacity = '1';
                        }, 50);
                    }
                    hideCategoryLoading();
                }, 300);
            });
        });

        // Initialize chart animations
        initializeCategoryAnimations();
    });

    // Enhanced functionality functions for category analysis
    function showCategoryLoading() {
        document.querySelectorAll('.chart-loading').forEach(loader => {
            loader.classList.remove('d-none');
        });
    }

    function hideCategoryLoading() {
        setTimeout(() => {
            document.querySelectorAll('.chart-loading').forEach(loader => {
                loader.classList.add('d-none');
            });
        }, 500);
    }

    function initializeCategoryAnimations() {
        // Add transition styles to chart containers
        document.querySelectorAll('.category-chart').forEach(chart => {
            chart.style.transition = 'opacity 0.3s ease-in-out';
            chart.style.opacity = '1';
        });
    }

    function refreshChart(chartType) {
        showCategoryLoading();

        // Simulate data refresh
        setTimeout(() => {
            if (window.categoryCharts && window.categoryCharts[chartType]) {
                window.categoryCharts[chartType].updateOptions({
                    chart: {
                        animations: {
                            enabled: true,
                            easing: 'easeinout',
                            speed: 800
                        }
                    }
                });
            }
            hideCategoryLoading();

            // Show success message
            showCategoryNotification('داده‌های نمودار با موفقیت بروزرسانی شد', 'success');
        }, 1000);
    }

    function fullscreenChart(chartId) {
        const chartElement = document.getElementById(chartId);
        if (chartElement.requestFullscreen) {
            chartElement.requestFullscreen();
        } else if (chartElement.webkitRequestFullscreen) {
            chartElement.webkitRequestFullscreen();
        } else if (chartElement.msRequestFullscreen) {
            chartElement.msRequestFullscreen();
        }
    }

    function downloadChart(chartId) {
        showCategoryNotification('در حال دانلود نمودار...', 'info');

        // Simulate download process
        setTimeout(() => {
            showCategoryNotification('نمودار با موفقیت دانلود شد', 'success');
        }, 1500);
    }

    function refreshCategoryData() {
        showCategoryNotification('در حال بروزرسانی داده‌های دسته‌بندی‌ها...', 'info');

        // Simulate refresh process
        setTimeout(() => {
            showCategoryNotification('داده‌ها با موفقیت بروزرسانی شدند', 'success');
        }, 2000);
    }

    function exportCategoryData(format) {
        showCategoryNotification('در حال آماده‌سازی فایل ' + format.toUpperCase() + '...', 'info');

        // Simulate export process
        setTimeout(() => {
            showCategoryNotification('فایل با موفقیت دانلود شد', 'success');
        }, 2000);
    }

    function showCategorySettings() {
        showCategoryNotification('تنظیمات نمایش در حال بارگذاری...', 'info');
    }

    function sortCategories(sortBy) {
        showCategoryNotification('در حال مرتب‌سازی بر اساس ' + (sortBy === 'count' ? 'تعداد' : 'رشد') + '...', 'info');

        // Simulate sorting
        setTimeout(() => {
            showCategoryNotification('مرتب‌سازی انجام شد', 'success');
        }, 1000);
    }

    function showCategoryNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} 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);

        // Auto remove after 3 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 3000);
    }
</script>