<div class="tab-pane fade" id="trendsAnalysis" role="tabpanel">
    <!-- Header Section with Enhanced Design -->
    <div class="trends-header-section mb-4">
        <div class="row align-items-center">
            <div class="col-md-6">
                <div class="trends-title-wrapper">
                    <h4 class="trends-main-title">
                        <i class="fas fa-chart-line text-primary me-2"></i>
                        تحلیل روند رشد
                    </h4>
                    <p class="trends-subtitle text-muted mb-0">
                        بررسی و تحلیل روند رشد مکان‌ها و دسته‌بندی‌ها
                    </p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="trends-controls d-flex justify-content-end">
                    <div class="btn-group trends-toggle-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" data-trend-chart="weekly">
                            <i class="fas fa-calendar-week me-1"></i>
                            روند هفتگی
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-trend-chart="categories">
                            <i class="fas fa-layer-group me-1"></i>
                            رشد دسته‌بندی‌ها
                        </button>
                    </div>
                    <div class="dropdown ms-2">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-download me-1"></i>
                            خروجی
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="exportTrendData('png')">
                                <i class="fas fa-image me-2"></i>تصویر PNG
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportTrendData('pdf')">
                                <i class="fas fa-file-pdf me-2"></i>فایل PDF
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportTrendData('excel')">
                                <i class="fas fa-file-excel me-2"></i>فایل Excel
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Charts Section -->
    <div class="row">
        <!-- Weekly Growth Chart -->
        <div class="col-lg-8 trend-chart" id="weeklyGrowth">
            <div class="card card-analytics trends-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-area me-2"></i>
                            نمودار روند رشد هفتگی
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('weekly')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('weeklyGrowthChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></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="weeklyGrowthChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Weekly Growth Statistics -->
        <div class="col-lg-4 trend-chart" id="weeklyGrowthStats">
            <div class="card card-analytics trends-stats-card">
                <div class="card-header bg-gradient-info text-white">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-table me-2"></i>
                        آمار رشد هفتگی
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 trends-stats-table">
                            <thead class="table-light">
                                <tr>
                                    <th class="border-0">هفته</th>
                                    <th class="border-0 text-center">تعداد</th>
                                    <th class="border-0 text-center">رشد</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($trendAnalysis['weekly'] as $index => $week)
                                <tr class="trends-stats-row">
                                    <td class="fw-medium">{{ $week['week'] }}</td>
                                    <td class="text-center">
                                        <span class="badge bg-light text-dark">{{ number_format($week['count']) }}</span>
                                    </td>
                                    <td class="text-center">
                                        <span class="trend-indicator-enhanced {{ $week['growth'] >= 0 ? 'positive' : 'negative' }}">
                                            <i class="fas fa-{{ $week['growth'] >= 0 ? 'arrow-up' : 'arrow-down' }}"></i>
                                            {{ abs($week['growth']) }}%
                                        </span>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <!-- Summary Statistics -->
                    <div class="trends-summary p-3 bg-light">
                        <div class="row text-center">
                            <div class="col-4">
                                <div class="summary-item">
                                    <div class="summary-value text-primary">{{ number_format(collect($trendAnalysis['weekly'])->sum('count')) }}</div>
                                    <div class="summary-label">کل مکان‌ها</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="summary-item">
                                    <div class="summary-value text-success">{{ number_format(collect($trendAnalysis['weekly'])->avg('growth'), 1) }}%</div>
                                    <div class="summary-label">میانگین رشد</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="summary-item">
                                    <div class="summary-value text-info">{{ count($trendAnalysis['weekly']) }}</div>
                                    <div class="summary-label">تعداد هفته</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Categories Growth Chart (hidden initially) -->
        <div class="col-12 trend-chart" id="categoriesGrowth" style="display: none;">
            <div class="card card-analytics trends-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('categories')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('categoriesGrowthChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></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="categoriesGrowthChart"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Categories Growth Cards Section -->
    <div class="card card-analytics trends-categories-section mt-4">
        <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-trophy me-2"></i>
                    دسته‌بندی‌های با بیشترین رشد در ماه اخیر
                </h5>
                <div class="header-actions">
                    <span class="badge bg-light text-dark">{{ count($trendAnalysis['categories']) }} دسته‌بندی</span>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                @foreach ($trendAnalysis['categories'] as $index => $category)
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card trends-category-card h-100 {{ $category['growth'] >= 0 ? 'border-success' : 'border-danger' }}">
                            <div class="card-body">
                                <!-- Category Header -->
                                <div class="d-flex justify-content-between align-items-start mb-3">
                                    <div class="category-info flex-grow-1">
                                        <h6 class="card-title fw-bold mb-1">{{ $category['category'] }}</h6>
                                        <div class="category-rank">
                                            <span class="badge bg-primary">رتبه {{ $index + 1 }}</span>
                                        </div>
                                    </div>
                                    <div class="category-growth">
                                        <span class="trend-indicator-large {{ $category['growth'] >= 0 ? 'positive' : 'negative' }}">
                                            <i class="fas fa-{{ $category['growth'] >= 0 ? 'arrow-up' : 'arrow-down' }}"></i>
                                            {{ abs($category['growth']) }}%
                                        </span>
                                    </div>
                                </div>

                                <!-- Statistics -->
                                <div class="category-stats mb-3">
                                    <div class="row text-center">
                                        <div class="col-6">
                                            <div class="stat-item">
                                                <div class="stat-value text-muted">{{ number_format($category['previous']) }}</div>
                                                <div class="stat-label">ماه قبل</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="stat-item">
                                                <div class="stat-value text-primary">{{ number_format($category['current']) }}</div>
                                                <div class="stat-label">ماه جاری</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Progress Bar -->
                                <div class="category-progress">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="progress-label">میزان رشد</span>
                                        <span class="progress-value">{{ abs($category['growth']) }}%</span>
                                    </div>
                                    <div class="progress" style="height: 8px;">
                                        <div class="progress-bar bg-gradient-{{ $category['growth'] >= 0 ? 'success' : 'danger' }}"
                                             role="progressbar"
                                             style="width: {{ min(100, abs($category['growth'])) }}%"
                                             aria-valuenow="{{ abs($category['growth']) }}"
                                             aria-valuemin="0"
                                             aria-valuemax="100">
                                        </div>
                                    </div>
                                </div>

                                <!-- Change Indicator -->
                                <div class="change-indicator mt-3 text-center">
                                    @if($category['growth'] > 0)
                                        <small class="text-success">
                                            <i class="fas fa-chart-line me-1"></i>
                                            افزایش {{ $category['current'] - $category['previous'] }} مکان
                                        </small>
                                    @elseif($category['growth'] < 0)
                                        <small class="text-danger">
                                            <i class="fas fa-chart-line-down me-1"></i>
                                            کاهش {{ $category['previous'] - $category['current'] }} مکان
                                        </small>
                                    @else
                                        <small class="text-muted">
                                            <i class="fas fa-minus me-1"></i>
                                            بدون تغییر
                                        </small>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>

    <!-- Forecast and Recommendations Section -->
    <div class="row mt-4">
        <div class="col-md-6">
            <div class="card card-analytics trends-forecast-card">
                <div class="card-header bg-gradient-primary text-white">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-crystal-ball me-2"></i>
                        پیش‌بینی رشد آینده
                    </h5>
                </div>
                <div class="card-body">
                    <div class="forecast-periods">
                        <div class="row text-center">
                            <div class="col-md-4">
                                <div class="forecast-item">
                                    <div class="forecast-period">
                                        <i class="fas fa-calendar-alt text-primary mb-2"></i>
                                        <h6 class="text-muted mb-2">ماه آینده</h6>
                                    </div>
                                    <div class="forecast-value">
                                        <div class="display-5 fw-bold text-primary">
                                            {{ ($trendAnalysis['forecast']['one_month'] > 0 ? '+' : '') }}{{ $trendAnalysis['forecast']['one_month'] ?? 0 }}%
                                        </div>
                                        <div class="forecast-confidence">
                                            <small class="text-muted">اطمینان: 85%</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="forecast-item">
                                    <div class="forecast-period">
                                        <i class="fas fa-calendar-week text-success mb-2"></i>
                                        <h6 class="text-muted mb-2">سه ماه آینده</h6>
                                    </div>
                                    <div class="forecast-value">
                                        <div class="display-5 fw-bold text-success">
                                            {{ ($trendAnalysis['forecast']['three_months'] > 0 ? '+' : '') }}{{ $trendAnalysis['forecast']['three_months'] ?? 0 }}%
                                        </div>
                                        <div class="forecast-confidence">
                                            <small class="text-muted">اطمینان: 75%</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="forecast-item">
                                    <div class="forecast-period">
                                        <i class="fas fa-calendar text-info mb-2"></i>
                                        <h6 class="text-muted mb-2">شش ماه آینده</h6>
                                    </div>
                                    <div class="forecast-value">
                                        <div class="display-5 fw-bold text-info">
                                            {{ ($trendAnalysis['forecast']['six_months'] > 0 ? '+' : '') }}{{ $trendAnalysis['forecast']['six_months'] ?? 0 }}%
                                        </div>
                                        <div class="forecast-confidence">
                                            <small class="text-muted">اطمینان: 65%</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Forecast Details -->
                    <div class="forecast-details mt-4 p-3 bg-light rounded">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <i class="fas fa-database text-primary me-2"></i>
                                    <span class="detail-label">مبنای محاسبه:</span>
                                    <span class="detail-value">{{ $trendAnalysis['forecast']['based_on'] ?? 12 }} ماه گذشته</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <i class="fas fa-chart-line text-success me-2"></i>
                                    <span class="detail-label">الگوریتم:</span>
                                    <span class="detail-value">رگرسیون خطی</span>
                                </div>
                            </div>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                پیش‌بینی‌ها بر اساس الگوی رشد تاریخی و روندهای فعلی محاسبه شده‌اند.
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card card-analytics trends-recommendations-card">
                <div class="card-header bg-gradient-success text-white">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-lightbulb me-2"></i>
                        توصیه‌های تحلیلی
                    </h5>
                </div>
                <div class="card-body">
                    <div class="recommendations-list">
                        <div class="recommendation-item mb-3 p-3 border-start border-primary border-4 bg-light">
                            <div class="d-flex align-items-start">
                                <div class="recommendation-icon me-3">
                                    <i class="fas fa-chart-line text-primary fs-4"></i>
                                </div>
                                <div class="recommendation-content">
                                    <h6 class="recommendation-title text-primary mb-1">تمرکز بر رشد</h6>
                                    <p class="recommendation-text mb-0">
                                        تمرکز بیشتر بر دسته‌بندی <strong>{{ $trendAnalysis['categories'][0]['category'] ?? 'هتل‌ها' }}</strong>
                                        با توجه به رشد قابل توجه آن
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="recommendation-item mb-3 p-3 border-start border-success border-4 bg-light">
                            <div class="d-flex align-items-start">
                                <div class="recommendation-icon me-3">
                                    <i class="fas fa-map-marker-alt text-success fs-4"></i>
                                </div>
                                <div class="recommendation-content">
                                    <h6 class="recommendation-title text-success mb-1">توسعه جغرافیایی</h6>
                                    <p class="recommendation-text mb-0">
                                        افزودن مکان‌های بیشتر در استان <strong>{{ $trendAnalysis['top_province'] ?? 'تهران' }}</strong>
                                        برای حفظ موقعیت رهبری
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="recommendation-item mb-3 p-3 border-start border-warning border-4 bg-light">
                            <div class="d-flex align-items-start">
                                <div class="recommendation-icon me-3">
                                    <i class="fas fa-star text-warning fs-4"></i>
                                </div>
                                <div class="recommendation-content">
                                    <h6 class="recommendation-title text-warning mb-1">بهبود کیفیت</h6>
                                    <p class="recommendation-text mb-0">
                                        بهبود کیفیت مکان‌های دسته <strong>{{ $categoryAnalytics['distribution']['labels'][0] ?? 'رستوران‌ها' }}</strong>
                                        برای افزایش رضایت کاربران
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="recommendation-item mb-0 p-3 border-start border-info border-4 bg-light">
                            <div class="d-flex align-items-start">
                                <div class="recommendation-icon me-3">
                                    <i class="fas fa-tasks text-info fs-4"></i>
                                </div>
                                <div class="recommendation-content">
                                    <h6 class="recommendation-title text-info mb-1">برنامه‌ریزی استراتژیک</h6>
                                    <p class="recommendation-text mb-0">
                                        برنامه‌ریزی برای ماه <strong>{{ $timeframeAnalytics['monthly']['labels'][0] ?? 'شهریور' }}</strong>
                                        با توجه به روند رشد پیش‌بینی شده
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="recommendations-actions mt-4 pt-3 border-top">
                        <div class="d-flex justify-content-between">
                            <button class="btn btn-outline-primary btn-sm" onclick="generateDetailedReport()">
                                <i class="fas fa-file-alt me-1"></i>
                                گزارش تفصیلی
                            </button>
                            <button class="btn btn-outline-success btn-sm" onclick="exportRecommendations()">
                                <i class="fas fa-download me-1"></i>
                                دانلود توصیه‌ها
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Extract weekly data
        const weeklyLabels = [];
        const weeklyData = [];
        const weeklyGrowth = [];

        @foreach ($trendAnalysis['weekly'] as $week)
            weeklyLabels.push('{{ $week['week'] }}');
            weeklyData.push({{ $week['count'] }});
            weeklyGrowth.push({{ $week['growth'] }});
        @endforeach

        // Enhanced Weekly Growth Chart Configuration
        const weeklyGrowthOptions = {
            series: [{
                name: 'تعداد مکان‌ها',
                type: 'column',
                data: weeklyData
            }, {
                name: 'درصد رشد',
                type: 'line',
                data: weeklyGrowth
            }],
            chart: {
                height: 400,
                type: 'line',
                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: 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: weeklyLabels,
            xaxis: {
                type: 'category',
                labels: {
                    rotate: -45,
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                axisBorder: {
                    show: true,
                    color: '#e0e6ed'
                },
                axisTicks: {
                    show: true,
                    color: '#e0e6ed'
                }
            },
            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,
                xaxis: {
                    lines: {
                        show: true
                    }
                },
                yaxis: {
                    lines: {
                        show: true
                    }
                }
            },
            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 weeklyGrowthChart = new ApexCharts(document.querySelector("#weeklyGrowthChart"), weeklyGrowthOptions);
        weeklyGrowthChart.render();

        // Extract categories growth data
        const categoryLabels = [];
        const categoryGrowths = [];
        const categoryColors = [];

        @foreach ($trendAnalysis['categories'] as $category)
            categoryLabels.push('{{ $category['category'] }}');
            categoryGrowths.push({{ $category['growth'] }});
            categoryColors.push('{{ $category['growth'] >= 0 ? '#28a745' : '#dc3545' }}');
        @endforeach

        // Enhanced Categories Growth Chart Configuration
        const categoriesGrowthOptions = {
            series: [{
                name: 'درصد رشد',
                data: categoryGrowths
            }],
            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,
                    horizontal: true,
                    distributed: true,
                    dataLabels: {
                        position: 'center'
                    },
                    barHeight: '70%'
                }
            },
            colors: categoryColors,
            dataLabels: {
                enabled: true,
                formatter: function (val) {
                    return val + '%';
                },
                textAnchor: 'middle',
                offsetX: 0,
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ['#fff']
                }
            },
            legend: {
                show: false
            },
            xaxis: {
                categories: categoryLabels,
                labels: {
                    formatter: function (val) {
                        return val + '%';
                    },
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                axisBorder: {
                    show: true,
                    color: '#e0e6ed'
                },
                axisTicks: {
                    show: true,
                    color: '#e0e6ed'
                }
            },
            yaxis: {
                labels: {
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                }
            },
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3,
                xaxis: {
                    lines: {
                        show: true
                    }
                },
                yaxis: {
                    lines: {
                        show: false
                    }
                }
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val) {
                        return val + '% رشد';
                    }
                }
            }
        };

        const categoriesGrowthChart = new ApexCharts(document.querySelector("#categoriesGrowthChart"), categoriesGrowthOptions);
        categoriesGrowthChart.render();

        // Store chart instances for later use
        window.trendsCharts = {
            weekly: weeklyGrowthChart,
            categories: categoriesGrowthChart
        };

        // Enhanced Trend chart toggle functionality
        const trendChartButtons = document.querySelectorAll('[data-trend-chart]');
        const trendCharts = document.querySelectorAll('.trend-chart');

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

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

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

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

                // Show selected chart with animation
                const selectedChart = this.getAttribute('data-trend-chart');
                setTimeout(() => {
                    if (selectedChart === 'weekly') {
                        document.getElementById('weeklyGrowth').style.display = 'block';
                        document.getElementById('weeklyGrowthStats').style.display = 'block';
                        setTimeout(() => {
                            document.getElementById('weeklyGrowth').style.opacity = '1';
                            document.getElementById('weeklyGrowthStats').style.opacity = '1';
                        }, 50);
                    } else if (selectedChart === 'categories') {
                        document.getElementById('categoriesGrowth').style.display = 'block';
                        setTimeout(() => {
                            document.getElementById('categoriesGrowth').style.opacity = '1';
                        }, 50);
                    }
                    hideChartLoading();
                }, 300);
            });
        });

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

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

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

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

    function refreshChart(chartType) {
        showChartLoading();

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

            // Show success message
            showNotification('داده‌های نمودار با موفقیت بروزرسانی شد', '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 exportTrendData(format) {
        showNotification('در حال آماده‌سازی فایل ' + format.toUpperCase() + '...', 'info');

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

    function generateDetailedReport() {
        showNotification('در حال تولید گزارش تفصیلی...', 'info');

        // Simulate report generation
        setTimeout(() => {
            showNotification('گزارش تفصیلی آماده شد', 'success');
        }, 3000);
    }

    function exportRecommendations() {
        showNotification('در حال دانلود توصیه‌ها...', 'info');

        // Simulate export
        setTimeout(() => {
            showNotification('فایل توصیه‌ها دانلود شد', 'success');
        }, 1500);
    }

    function showNotification(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>