@extends('admin.layouts.app')

@section('title', 'تحلیل پیش‌بینی')

@section('content')
<div class="container-fluid">
    <!-- Modern Header Section -->
    <div class="predictive-analytics-header">
        <div class="header-content">
            <div class="header-text">
                <h1 class="header-title">
                    <i class="fas fa-crystal-ball me-3"></i>
                    تحلیل پیش‌بینی
                </h1>
                <p class="header-subtitle">
                    پیش‌بینی هوشمند روندها و الگوهای آینده بر اساس داده‌های تاریخی و یادگیری ماشین
                </p>
            </div>
            <div class="header-controls">
                <div class="btn-group me-2" role="group">
                    <button type="button" class="btn btn-outline-primary active" data-predictive-view="forecast">
                        <i class="fas fa-chart-line me-1"></i>
                        پیش‌بینی
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-predictive-view="trends">
                        <i class="fas fa-trending-up me-1"></i>
                        روندها
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-predictive-view="seasonality">
                        <i class="fas fa-calendar-alt me-1"></i>
                        فصلی‌بودن
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-predictive-view="correlation">
                        <i class="fas fa-project-diagram me-1"></i>
                        همبستگی
                    </button>
                </div>
                <div class="dropdown">
                    <button class="btn btn-primary 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="refreshPredictiveData()">
                            <i class="fas fa-sync me-2"></i>بروزرسانی مدل
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportPredictiveData('excel')">
                            <i class="fas fa-file-excel me-2"></i>خروجی Excel
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportPredictiveData('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="showPredictiveSettings()">
                            <i class="fas fa-sliders-h me-2"></i>تنظیمات مدل
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Overview Cards -->
    <div class="row mb-4" id="predictive-overview-cards">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="predictive-overview-card">
                <div class="card-icon bg-primary">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ $predictiveData['accuracy'] ?? 85 }}%</div>
                    <div class="card-label">دقت پیش‌بینی</div>
                    <div class="card-trend positive">
                        <i class="fas fa-check-circle me-1"></i>
                        قابل اعتماد
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="predictive-overview-card">
                <div class="card-icon bg-success">
                    <i class="fas fa-arrow-up"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ $forecastData['next_month_growth'] ?? '+12' }}%</div>
                    <div class="card-label">رشد پیش‌بینی شده</div>
                    <div class="card-trend positive">
                        <i class="fas fa-trending-up me-1"></i>
                        ماه آینده
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="predictive-overview-card">
                <div class="card-icon bg-info">
                    <i class="fas fa-calendar-check"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ $seasonalityData['peak_season'] ?? 'بهار' }}</div>
                    <div class="card-label">فصل پیک</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-leaf me-1"></i>
                        الگوی فصلی
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="predictive-overview-card">
                <div class="card-icon bg-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ $correlationData['risk_level'] ?? 'کم' }}</div>
                    <div class="card-label">سطح ریسک</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-shield-alt me-1"></i>
                        تحلیل ریسک
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Forecast Section -->
    <div class="predictive-view" id="forecast-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-chart-line text-primary me-2"></i>
                                پیش‌بینی روند آینده
                            </h5>
                            <p class="text-muted mb-0">پیش‌بینی 6 ماه آینده بر اساس الگوهای تاریخی</p>
                        </div>
                        <div class="chart-actions">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active" onclick="toggleForecastPeriod('3months')">
                                    3 ماه
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleForecastPeriod('6months')">
                                    6 ماه
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleForecastPeriod('12months')">
                                    12 ماه
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="forecast-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="forecast-insights-card">
                    <div class="insights-header">
                        <h6 class="mb-0">
                            <i class="fas fa-lightbulb text-warning me-2"></i>
                            بینش‌های پیش‌بینی
                        </h6>
                    </div>
                    <div class="insights-body">
                        <div class="insight-item">
                            <div class="insight-icon bg-success">
                                <i class="fas fa-arrow-up"></i>
                            </div>
                            <div class="insight-content">
                                <div class="insight-title">روند صعودی</div>
                                <div class="insight-text">انتظار رشد {{ $forecastData['expected_growth'] ?? '15' }}% در 3 ماه آینده</div>
                            </div>
                        </div>
                        <div class="insight-item">
                            <div class="insight-icon bg-info">
                                <i class="fas fa-calendar"></i>
                            </div>
                            <div class="insight-content">
                                <div class="insight-title">بهترین زمان</div>
                                <div class="insight-text">{{ $seasonalityData['best_month'] ?? 'فروردین' }} بهترین ماه برای رشد</div>
                            </div>
                        </div>
                        <div class="insight-item">
                            <div class="insight-icon bg-warning">
                                <i class="fas fa-exclamation-circle"></i>
                            </div>
                            <div class="insight-content">
                                <div class="insight-title">نقطه توجه</div>
                                <div class="insight-text">احتمال کاهش در {{ $forecastData['risk_period'] ?? 'تابستان' }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Trends Section -->
    <div class="predictive-view d-none" id="trends-view">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-trending-up text-success me-2"></i>
                                تحلیل روند کوتاه‌مدت
                            </h5>
                            <p class="text-muted mb-0">روندهای 30 روز گذشته و پیش‌بینی 7 روز آینده</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="short-trend-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-chart-area text-info me-2"></i>
                                تحلیل روند بلندمدت
                            </h5>
                            <p class="text-muted mb-0">روندهای 12 ماه گذشته و پیش‌بینی 3 ماه آینده</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="long-trend-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-12 mb-4">
                <div class="trend-analysis-card">
                    <div class="analysis-header">
                        <h6 class="mb-0">
                            <i class="fas fa-chart-bar text-primary me-2"></i>
                            تحلیل عمقی روندها
                        </h6>
                    </div>
                    <div class="analysis-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="trend-metric">
                                    <div class="metric-value">{{ $predictiveData['trend_strength'] ?? 'قوی' }}</div>
                                    <div class="metric-label">قدرت روند</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="trend-metric">
                                    <div class="metric-value">{{ $predictiveData['volatility'] ?? 'متوسط' }}</div>
                                    <div class="metric-label">نوسان</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="trend-metric">
                                    <div class="metric-value">{{ $predictiveData['momentum'] ?? 'مثبت' }}</div>
                                    <div class="metric-label">مومنتوم</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="trend-metric">
                                    <div class="metric-value">{{ $predictiveData['stability'] ?? 'پایدار' }}</div>
                                    <div class="metric-label">پایداری</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Seasonality Section -->
    <div class="predictive-view d-none" id="seasonality-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-calendar-alt text-warning me-2"></i>
                                الگوهای فصلی
                            </h5>
                            <p class="text-muted mb-0">مقایسه الگوهای فصلی در سال‌های مختلف</p>
                        </div>
                        <div class="chart-actions">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active" onclick="toggleSeasonalView('monthly')">
                                    ماهانه
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleSeasonalView('quarterly')">
                                    فصلی
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleSeasonalView('weekly')">
                                    هفتگی
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="seasonality-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="seasonal-insights-card">
                    <div class="insights-header">
                        <h6 class="mb-0">
                            <i class="fas fa-leaf text-success me-2"></i>
                            الگوهای فصلی
                        </h6>
                    </div>
                    <div class="insights-body">
                        <div class="seasonal-pattern">
                            <div class="pattern-header">
                                <span class="pattern-season">بهار</span>
                                <span class="pattern-score high">بالا</span>
                            </div>
                            <div class="pattern-bar">
                                <div class="pattern-fill" style="width: 85%"></div>
                            </div>
                        </div>
                        <div class="seasonal-pattern">
                            <div class="pattern-header">
                                <span class="pattern-season">تابستان</span>
                                <span class="pattern-score medium">متوسط</span>
                            </div>
                            <div class="pattern-bar">
                                <div class="pattern-fill" style="width: 60%"></div>
                            </div>
                        </div>
                        <div class="seasonal-pattern">
                            <div class="pattern-header">
                                <span class="pattern-season">پاییز</span>
                                <span class="pattern-score high">بالا</span>
                            </div>
                            <div class="pattern-bar">
                                <div class="pattern-fill" style="width: 75%"></div>
                            </div>
                        </div>
                        <div class="seasonal-pattern">
                            <div class="pattern-header">
                                <span class="pattern-season">زمستان</span>
                                <span class="pattern-score low">پایین</span>
                            </div>
                            <div class="pattern-bar">
                                <div class="pattern-fill" style="width: 40%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Correlation Section -->
    <div class="predictive-view d-none" id="correlation-view">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-project-diagram text-danger me-2"></i>
                                ماتریس همبستگی
                            </h5>
                            <p class="text-muted mb-0">همبستگی بین متغیرهای مختلف</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="correlation-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 mb-4">
                <div class="predictive-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-network-wired text-info me-2"></i>
                                تحلیل عوامل تأثیرگذار
                            </h5>
                            <p class="text-muted mb-0">عوامل مؤثر بر روندهای آینده</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="factors-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Advanced Settings Panel -->
    <div class="predictive-settings-panel d-none" id="predictive-settings">
        <div class="settings-header">
            <h6 class="mb-0">
                <i class="fas fa-sliders-h me-2"></i>
                تنظیمات مدل پیش‌بینی
            </h6>
            <button class="btn btn-sm btn-outline-secondary" onclick="hidePredictiveSettings()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="settings-body">
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">مدل پیش‌بینی</label>
                    <select class="form-select" id="prediction-model">
                        <option value="linear">رگرسیون خطی</option>
                        <option value="polynomial">رگرسیون چندجمله‌ای</option>
                        <option value="exponential">نمایی</option>
                        <option value="arima">ARIMA</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">بازه زمانی</label>
                    <select class="form-select" id="time-horizon">
                        <option value="3">3 ماه</option>
                        <option value="6" selected>6 ماه</option>
                        <option value="12">12 ماه</option>
                        <option value="24">24 ماه</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">سطح اطمینان</label>
                    <select class="form-select" id="confidence-level">
                        <option value="80">80%</option>
                        <option value="90" selected>90%</option>
                        <option value="95">95%</option>
                        <option value="99">99%</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">نوع داده</label>
                    <select class="form-select" id="data-type">
                        <option value="locations">مکان‌ها</option>
                        <option value="ratings">امتیازات</option>
                        <option value="users">کاربران</option>
                        <option value="all" selected>همه</option>
                    </select>
                </div>
            </div>
            <div class="settings-actions mt-3">
                <button class="btn btn-primary" onclick="applyPredictiveSettings()">
                    <i class="fas fa-check me-1"></i>
                    اعمال تنظیمات
                </button>
                <button class="btn btn-outline-secondary" onclick="resetPredictiveSettings()">
                    <i class="fas fa-undo me-1"></i>
                    بازنشانی
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('styles')
<style>
    /* Modern Predictive Analytics Styles */
    .predictive-analytics-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .predictive-analytics-header::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="crystal" width="50" height="50" patternUnits="userSpaceOnUse"><polygon points="25,5 45,20 25,35 5,20" fill="white" opacity="0.05"/><circle cx="25" cy="25" r="2" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23crystal)"/></svg>');
        pointer-events: none;
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
        z-index: 1;
    }

    .header-title {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .header-subtitle {
        font-size: 1.1rem;
        opacity: 0.9;
        margin-bottom: 0;
        line-height: 1.5;
    }

    .header-controls .btn {
        margin-left: 0.5rem;
        border-color: rgba(255,255,255,0.3);
        color: white;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;
    }

    .header-controls .btn:hover {
        background: rgba(255,255,255,0.2);
        border-color: rgba(255,255,255,0.5);
        transform: translateY(-2px);
    }

    .header-controls .btn.active {
        background: rgba(255,255,255,0.2);
        border-color: rgba(255,255,255,0.5);
    }

    /* Overview Cards */
    .predictive-overview-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: 0 4px 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;
        position: relative;
        overflow: hidden;
    }

    .predictive-overview-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    }

    .predictive-overview-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0,0,0,0.12);
    }

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

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

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

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

    .predictive-overview-card .card-trend {
        font-size: 0.8rem;
        font-weight: 500;
        display: flex;
        align-items: center;
    }

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

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

    .predictive-overview-card .card-trend.neutral {
        color: #6c757d;
    }

    /* Chart Cards */
    .predictive-chart-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .chart-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
    }

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

    .chart-title p {
        font-size: 0.9rem;
        margin-bottom: 0;
    }

    .chart-actions .btn {
        border-radius: 8px;
        padding: 0.5rem 0.75rem;
        transition: all 0.3s ease;
    }

    .chart-actions .btn.active {
        background: #667eea;
        border-color: #667eea;
        color: white;
    }

    .chart-body {
        padding: 1.5rem;
    }

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

    /* Forecast Insights Card */
    .forecast-insights-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .insights-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
    }

    .insights-body {
        padding: 1.5rem;
    }

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

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

    .insight-item:last-child {
        margin-bottom: 0;
    }

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

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

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

    /* Trend Analysis Card */
    .trend-analysis-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
    }

    .analysis-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
    }

    .analysis-body {
        padding: 1.5rem;
    }

    .trend-metric {
        text-align: center;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 12px;
        transition: all 0.3s ease;
    }

    .trend-metric:hover {
        background: #e9ecef;
        transform: translateY(-2px);
    }

    .trend-metric .metric-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }

    .trend-metric .metric-label {
        font-size: 0.9rem;
        color: #6c757d;
    }

    /* Seasonal Insights Card */
    .seasonal-insights-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .seasonal-pattern {
        margin-bottom: 1.5rem;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 12px;
    }

    .seasonal-pattern:last-child {
        margin-bottom: 0;
    }

    .pattern-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.5rem;
    }

    .pattern-season {
        font-weight: 600;
        color: #2c3e50;
    }

    .pattern-score {
        font-size: 0.8rem;
        padding: 0.2rem 0.5rem;
        border-radius: 12px;
        font-weight: 500;
    }

    .pattern-score.high {
        background: #d4edda;
        color: #155724;
    }

    .pattern-score.medium {
        background: #fff3cd;
        color: #856404;
    }

    .pattern-score.low {
        background: #f8d7da;
        color: #721c24;
    }

    .pattern-bar {
        height: 8px;
        background: #e9ecef;
        border-radius: 4px;
        overflow: hidden;
    }

    .pattern-fill {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 4px;
        transition: width 0.3s ease;
    }

    /* Settings Panel */
    .predictive-settings-panel {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        margin-bottom: 2rem;
        overflow: hidden;
    }

    .settings-header {
        padding: 1rem 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .settings-body {
        padding: 1.5rem;
    }

    .settings-actions {
        display: flex;
        gap: 1rem;
    }

    /* View Management */
    .predictive-view {
        animation: fadeIn 0.3s ease;
    }

    .predictive-view.d-none {
        display: none !important;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .header-content {
            flex-direction: column;
            gap: 1rem;
        }

        .header-controls {
            width: 100%;
            justify-content: center;
        }

        .header-controls .btn-group {
            flex-wrap: wrap;
        }

        .predictive-overview-card {
            flex-direction: column;
            text-align: center;
        }

        .chart-header {
            flex-direction: column;
            gap: 1rem;
            align-items: flex-start;
        }

        .trend-metric {
            margin-bottom: 1rem;
        }
    }
</style>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/apexcharts@latest"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Predictive data from backend
    const predictiveData = @json($predictiveData ?? []);
    const seasonalityData = @json($seasonalityData ?? []);
    const forecastData = @json($forecastData ?? []);
    const correlationData = @json($correlationData ?? []);

    // Initialize the page
    initPredictiveAnalytics();

    function initPredictiveAnalytics() {
        // Initialize view management
        initViewManagement();

        // Initialize charts
        initForecastChart();
        initShortTrendChart();
        initLongTrendChart();
        initSeasonalityChart();
        initCorrelationChart();
        initFactorsChart();
    }

    function initViewManagement() {
        // Handle view switching
        document.querySelectorAll('[data-predictive-view]').forEach(button => {
            button.addEventListener('click', function() {
                const viewType = this.getAttribute('data-predictive-view');
                switchPredictiveView(viewType);

                // Update active button
                document.querySelectorAll('[data-predictive-view]').forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
            });
        });
    }

    function switchPredictiveView(viewType) {
        // Hide all views
        document.querySelectorAll('.predictive-view').forEach(view => {
            view.classList.add('d-none');
        });

        // Show selected view
        const targetView = document.getElementById(viewType + '-view');
        if (targetView) {
            targetView.classList.remove('d-none');
        }
    }

    function initForecastChart() {
        const historicalData = predictiveData.historical || {};
        const predictionData = predictiveData.predictions || {};

        const allMonths = [
            ...(historicalData.months || []),
            ...(predictionData.months || [])
        ];

        const historicalCounts = historicalData.counts || [];
        const predictionCounts = predictionData.counts || [];

        // Combine data for continuous line
        const combinedData = [
            ...historicalCounts,
            ...predictionCounts
        ];

        // Create prediction line starting from last historical point
        const predictionLine = [
            ...new Array(historicalCounts.length - 1).fill(null),
            historicalCounts[historicalCounts.length - 1] || 0,
            ...predictionCounts
        ];

        const options = {
            series: [{
                name: 'داده‌های تاریخی',
                data: [...historicalCounts, ...new Array(predictionCounts.length).fill(null)]
            }, {
                name: 'پیش‌بینی',
                data: predictionLine
            }],
            chart: {
                type: 'line',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                }
            },
            stroke: {
                curve: 'smooth',
                width: [3, 3],
                dashArray: [0, 5]
            },
            colors: ['#667eea', '#28a745'],
            xaxis: {
                categories: allMonths,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.5,
                    gradientToColors: ['#764ba2', '#20c997'],
                    inverseColors: false,
                    opacityFrom: 0.8,
                    opacityTo: 0.1,
                    stops: [0, 100]
                }
            },
            markers: {
                size: [4, 6],
                colors: ['#667eea', '#28a745'],
                strokeColors: '#fff',
                strokeWidth: 2,
                hover: {
                    size: 8
                }
            },
            tooltip: {
                shared: true,
                intersect: false,
                y: {
                    formatter: function (val) {
                        return val ? val + " مورد" : "---";
                    }
                }
            },
            legend: {
                position: 'top',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            }
        };

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

    function initShortTrendChart() {
        const shortTrendData = forecastData.short_trend || {};
        const dates = shortTrendData.dates || [];
        const actual = shortTrendData.actual || [];
        const ma7 = shortTrendData.ma7 || [];

        const options = {
            series: [{
                name: 'داده‌های واقعی',
                data: actual
            }, {
                name: 'میانگین متحرک 7 روزه',
                data: ma7
            }],
            chart: {
                type: 'area',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: [2, 3]
            },
            fill: {
                type: 'gradient',
                gradient: {
                    opacityFrom: 0.6,
                    opacityTo: 0.1
                }
            },
            colors: ['#667eea', '#28a745'],
            xaxis: {
                categories: dates,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مورد";
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#short-trend-chart"), options);
        chart.render();
        window.shortTrendChart = chart;
    }

    function initLongTrendChart() {
        const longTrendData = forecastData.long_trend || {};
        const months = longTrendData.months || [];
        const actual = longTrendData.actual || [];
        const ma30 = longTrendData.ma30 || [];
        const forecast = longTrendData.forecast || [];

        const options = {
            series: [{
                name: 'داده‌های تاریخی',
                data: actual
            }, {
                name: 'میانگین متحرک 30 روزه',
                data: ma30
            }, {
                name: 'پیش‌بینی 3 ماه',
                data: [...new Array(actual.length - 1).fill(null), actual[actual.length - 1], ...forecast]
            }],
            chart: {
                type: 'line',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            stroke: {
                curve: 'smooth',
                width: [2, 3, 3],
                dashArray: [0, 0, 5]
            },
            colors: ['#667eea', '#28a745', '#ffc107'],
            xaxis: {
                categories: [...months, ...['ماه +1', 'ماه +2', 'ماه +3']],
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val ? val + " مورد" : "---";
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#long-trend-chart"), options);
        chart.render();
        window.longTrendChart = chart;
    }

    function initSeasonalityChart() {
        const seasonalData = seasonalityData.monthly || [];
        const months = seasonalData.map(item => item.month) || [];
        const currentYear = new Date().getFullYear();
        const previousYear = currentYear - 1;

        const currentYearData = seasonalData.map(item => item.data[currentYear] || 0);
        const previousYearData = seasonalData.map(item => item.data[previousYear] || 0);

        const options = {
            series: [{
                name: previousYear.toString(),
                data: previousYearData
            }, {
                name: currentYear.toString(),
                data: currentYearData
            }],
            chart: {
                type: 'bar',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '55%',
                    endingShape: 'rounded'
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                show: true,
                width: 2,
                colors: ['transparent']
            },
            colors: ['#6c757d', '#667eea'],
            xaxis: {
                categories: months,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                opacity: 1
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مورد";
                    }
                }
            }
        };

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

    function initCorrelationChart() {
        const correlationMatrix = correlationData.matrix || [];
        const variables = correlationData.variables || ['مکان‌ها', 'امتیازات', 'کاربران', 'نظرات'];

        const options = {
            series: correlationMatrix,
            chart: {
                height: 350,
                type: 'heatmap',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            dataLabels: {
                enabled: true,
                style: {
                    colors: ['#fff']
                }
            },
            colors: ["#667eea"],
            xaxis: {
                categories: variables,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                categories: variables,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val.toFixed(2);
                    }
                }
            }
        };

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

    function initFactorsChart() {
        const factors = correlationData.factors || {};
        const factorNames = factors.names || ['زمان', 'مکان', 'کیفیت', 'تعامل'];
        const factorWeights = factors.weights || [0.3, 0.25, 0.25, 0.2];

        const options = {
            series: factorWeights.map(weight => weight * 100),
            chart: {
                type: 'donut',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            labels: factorNames,
            colors: ['#667eea', '#28a745', '#ffc107', '#dc3545'],
            plotOptions: {
                pie: {
                    donut: {
                        size: '70%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'مجموع تأثیر',
                                formatter: function () {
                                    return '100%';
                                }
                            }
                        }
                    }
                }
            },
            legend: {
                position: 'bottom',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val.toFixed(1) + '%';
                    }
                }
            }
        };

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

    // Chart toggle functions
    window.toggleForecastPeriod = function(period) {
        console.log('Toggling forecast period to:', period);

        // Update active button
        document.querySelectorAll('#forecast-view .chart-actions .btn').forEach(btn => btn.classList.remove('active'));
        event.target.classList.add('active');

        // Update chart based on period
        if (window.forecastChart) {
            // Here you would update the chart with different data based on period
            showNotification(`نمایش پیش‌بینی ${period === '3months' ? '3 ماهه' : period === '6months' ? '6 ماهه' : '12 ماهه'}`, 'info');
        }
    };

    window.toggleSeasonalView = function(viewType) {
        console.log('Toggling seasonal view to:', viewType);

        // Update active button
        document.querySelectorAll('#seasonality-view .chart-actions .btn').forEach(btn => btn.classList.remove('active'));
        event.target.classList.add('active');

        // Update chart based on view type
        if (window.seasonalityChart) {
            showNotification(`نمایش الگوی ${viewType === 'monthly' ? 'ماهانه' : viewType === 'quarterly' ? 'فصلی' : 'هفتگی'}`, 'info');
        }
    };

    // Global functions for external use
    window.refreshPredictiveData = function() {
        console.log('Refreshing predictive model...');
        showNotification('در حال بروزرسانی مدل پیش‌بینی...', 'info');

        // Simulate model refresh
        setTimeout(() => {
            showNotification('مدل پیش‌بینی بروزرسانی شد', 'success');
            location.reload();
        }, 2000);
    };

    window.exportPredictiveData = function(format) {
        console.log('Exporting predictive data as:', format);
        showNotification(`در حال تهیه گزارش ${format.toUpperCase()}...`, 'info');

        // Simulate export
        setTimeout(() => {
            showNotification(`گزارش ${format.toUpperCase()} آماده دانلود است`, 'success');
        }, 2000);
    };

    window.showPredictiveSettings = function() {
        const settingsPanel = document.getElementById('predictive-settings');
        if (settingsPanel) {
            settingsPanel.classList.remove('d-none');
        }
    };

    window.hidePredictiveSettings = function() {
        const settingsPanel = document.getElementById('predictive-settings');
        if (settingsPanel) {
            settingsPanel.classList.add('d-none');
        }
    };

    window.applyPredictiveSettings = function() {
        const model = document.getElementById('prediction-model').value;
        const horizon = document.getElementById('time-horizon').value;
        const confidence = document.getElementById('confidence-level').value;
        const dataType = document.getElementById('data-type').value;

        console.log('Applying predictive settings:', { model, horizon, confidence, dataType });
        showNotification('تنظیمات مدل اعمال شدند', 'success');

        // Hide settings panel
        hidePredictiveSettings();

        // Simulate settings application
        setTimeout(() => {
            location.reload();
        }, 1000);
    };

    window.resetPredictiveSettings = function() {
        document.getElementById('prediction-model').value = 'linear';
        document.getElementById('time-horizon').value = '6';
        document.getElementById('confidence-level').value = '90';
        document.getElementById('data-type').value = 'all';

        showNotification('تنظیمات بازنشانی شدند', 'success');
    };

    function showNotification(message, type = 'info') {
        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);

        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
});
</script>
@endsection