@extends('admin.layouts.app')

@section('title', 'تحلیل جغرافیایی')

@section('content')
<div class="container-fluid">
    <!-- Modern Header Section -->
    <div class="geographic-analytics-header">
        <div class="header-content">
            <div class="header-text">
                <h1 class="header-title">
                    <i class="fas fa-globe-asia 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-geo-view="overview">
                        <i class="fas fa-chart-area me-1"></i>
                        نمای کلی
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-geo-view="provinces">
                        <i class="fas fa-map me-1"></i>
                        استان‌ها
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-geo-view="cities">
                        <i class="fas fa-city me-1"></i>
                        شهرها
                    </button>
                    @if(isset($villagesData) && count($villagesData) > 0)
                    <button type="button" class="btn btn-outline-primary" data-geo-view="villages">
                        <i class="fas fa-home me-1"></i>
                        روستاها
                    </button>
                    @endif
                    <button type="button" class="btn btn-outline-primary" data-geo-view="heatmap">
                        <i class="fas fa-fire 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-filter me-1"></i>
                        فیلترها
                    </button>
                    <ul class="dropdown-menu">
                        <li><h6 class="dropdown-header">بازه زمانی</h6></li>
                        <li><a class="dropdown-item" href="#" onclick="applyGeoFilter('7')">
                            <i class="fas fa-calendar-week me-2"></i>7 روز گذشته
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="applyGeoFilter('30')">
                            <i class="fas fa-calendar-alt me-2"></i>30 روز گذشته
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="applyGeoFilter('90')">
                            <i class="fas fa-calendar me-2"></i>90 روز گذشته
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="exportGeoData('excel')">
                            <i class="fas fa-file-excel me-2"></i>خروجی Excel
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportGeoData('pdf')">
                            <i class="fas fa-file-pdf me-2"></i>گزارش PDF
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Geographic KPI Cards -->
    <div class="row mb-4" id="geographic-kpi-cards">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="geo-kpi-card">
                <div class="card-icon bg-primary">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ count($regionData ?? []) }}</div>
                    <div class="card-label">استان‌های فعال</div>
                    <div class="card-trend positive">
                        <i class="fas fa-arrow-up me-1"></i>
                        {{ round((count($regionData ?? []) / 31) * 100, 1) }}% پوشش کشور
                    </div>
                </div>
                <div class="card-progress">
                    <div class="progress-bar" style="width: {{ round((count($regionData ?? []) / 31) * 100, 1) }}%"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="geo-kpi-card">
                <div class="card-icon bg-success">
                    <i class="fas fa-city"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ count($cityPerformance ?? []) }}</div>
                    <div class="card-label">شهرهای فعال</div>
                    <div class="card-trend positive">
                        <i class="fas fa-chart-line me-1"></i>
                        رشد شهری
                    </div>
                </div>
                <div class="card-progress">
                    <div class="progress-bar" style="width: 75%"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="geo-kpi-card">
                <div class="card-icon bg-info">
                    <i class="fas fa-users"></i>
                </div>
                <div class="card-content">
                    @php
                        $totalLocations = 0;
                        if (isset($regionData) && is_array($regionData)) {
                            foreach($regionData as $region) {
                                if (is_array($region)) {
                                    $totalLocations += $region['count'] ?? 0;
                                } elseif (is_object($region)) {
                                    $totalLocations += $region->count ?? 0;
                                }
                            }
                        }
                    @endphp
                    <div class="card-value">{{ $totalLocations }}</div>
                    <div class="card-label">کل مکان‌ها</div>
                    <div class="card-trend positive">
                        <i class="fas fa-plus me-1"></i>
                        توزیع سراسری
                    </div>
                </div>
                <div class="card-progress">
                    <div class="progress-bar" style="width: 85%"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="geo-kpi-card">
                <div class="card-icon bg-warning">
                    <i class="fas fa-chart-pie"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">{{ count($populationDensity ?? []) }}</div>
                    <div class="card-label">مناطق پرتراکم</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-balance-scale me-1"></i>
                        تراکم متعادل
                    </div>
                </div>
                <div class="card-progress">
                    <div class="progress-bar" style="width: 60%"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overview Section -->
    <div class="geo-view" id="overview-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-globe text-primary 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="toggleMapLayer('locations')">
                                    مکان‌ها
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleMapLayer('heatmap')">
                                    نقشه حرارتی
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleMapLayer('clusters')">
                                    خوشه‌بندی
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="iran-interactive-map" class="map-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="geo-summary-card">
                    <div class="summary-header">
                        <h6 class="mb-0">
                            <i class="fas fa-chart-bar text-success me-2"></i>
                            آمار جغرافیایی
                        </h6>
                    </div>
                    <div class="summary-body">
                        <div class="summary-item">
                            <div class="summary-icon bg-primary">
                                <i class="fas fa-map-marker-alt"></i>
                            </div>
                            <div class="summary-content">
                                <div class="summary-value">{{ $topProvince['name'] ?? 'تهران' }}</div>
                                <div class="summary-label">استان برتر</div>
                                <div class="summary-detail">{{ $topProvince['count'] ?? 0 }} مکان</div>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-icon bg-success">
                                <i class="fas fa-building"></i>
                            </div>
                            <div class="summary-content">
                                <div class="summary-value">{{ $topCity['name'] ?? 'تهران' }}</div>
                                <div class="summary-label">شهر برتر</div>
                                <div class="summary-detail">{{ $topCity['count'] ?? 0 }} مکان</div>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-icon bg-info">
                                <i class="fas fa-percentage"></i>
                            </div>
                            <div class="summary-content">
                                <div class="summary-value">{{ $coveragePercentage ?? 75 }}%</div>
                                <div class="summary-label">پوشش جغرافیایی</div>
                                <div class="summary-detail">از کل کشور</div>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-icon bg-warning">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <div class="summary-content">
                                <div class="summary-value">{{ $growthRate ?? 15 }}%</div>
                                <div class="summary-label">نرخ رشد</div>
                                <div class="summary-detail">ماه گذشته</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Provinces Section -->
    <div class="geo-view d-none" id="provinces-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-map text-primary 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="toggleProvinceChart('bar')">
                                    <i class="fas fa-chart-bar"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleProvinceChart('pie')">
                                    <i class="fas fa-chart-pie"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleProvinceChart('treemap')">
                                    <i class="fas fa-th"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="provinces-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="provinces-ranking-card">
                    <div class="ranking-header">
                        <h6 class="mb-0">
                            <i class="fas fa-trophy text-warning me-2"></i>
                            رتبه‌بندی استان‌ها
                        </h6>
                    </div>
                    <div class="ranking-body">
                        @if(isset($regionData) && count($regionData) > 0)
                            @foreach(array_slice($regionData, 0, 10) as $index => $province)
                            @php
                                $provinceName = is_array($province) ? ($province['name'] ?? 'نامشخص') : (is_object($province) ? ($province->name ?? 'نامشخص') : 'نامشخص');
                                $provinceCount = is_array($province) ? ($province['count'] ?? 0) : (is_object($province) ? ($province->count ?? 0) : 0);
                                $totalCount = 0;
                                $maxCount = 1;
                                foreach($regionData as $item) {
                                    $count = is_array($item) ? ($item['count'] ?? 0) : (is_object($item) ? ($item->count ?? 0) : 0);
                                    $totalCount += $count;
                                    $maxCount = max($maxCount, $count);
                                }
                            @endphp
                            <div class="ranking-item">
                                <div class="ranking-position">
                                    <span class="position-number">{{ $index + 1 }}</span>
                                </div>
                                <div class="ranking-content">
                                    <div class="ranking-name">{{ $provinceName }}</div>
                                    <div class="ranking-value">{{ $provinceCount }} مکان</div>
                                    <div class="ranking-percentage">
                                        {{ $totalCount > 0 ? round(($provinceCount / $totalCount) * 100, 1) : 0 }}%
                                    </div>
                                </div>
                                <div class="ranking-bar">
                                    <div class="bar-fill" style="width: {{ round(($provinceCount / $maxCount) * 100, 1) }}%"></div>
                                </div>
                            </div>
                            @endforeach
                        @else
                            <div class="no-data">
                                <i class="fas fa-info-circle text-muted"></i>
                                <p>داده‌ای برای نمایش وجود ندارد</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Cities Section -->
    <div class="geo-view d-none" id="cities-view">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-city text-success me-2"></i>
                                عملکرد شهرهای برتر
                            </h5>
                            <p class="text-muted mb-0">مقایسه فعالیت در شهرهای مختلف</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="cities-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-users text-info me-2"></i>
                                تراکم جمعیت و فعالیت
                            </h5>
                            <p class="text-muted mb-0">رابطه بین تراکم جمعیت و فعالیت کاربران</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="population-density-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-12 mb-4">
                <div class="cities-table-card">
                    <div class="table-header">
                        <h6 class="mb-0">
                            <i class="fas fa-table text-primary me-2"></i>
                            جدول تفصیلی شهرها
                        </h6>
                    </div>
                    <div class="table-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>رتبه</th>
                                        <th>شهر</th>
                                        <th>تعداد مکان</th>
                                        <th>درصد</th>
                                        <th>رشد</th>
                                        <th>وضعیت</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if(isset($cityPerformance) && count($cityPerformance) > 0)
                                        @foreach(array_slice($cityPerformance, 0, 15) as $index => $city)
                                        @php
                                            $cityName = is_array($city) ? ($city['name'] ?? $city['city_name'] ?? 'نامشخص') : (is_object($city) ? ($city->name ?? $city->city_name ?? 'نامشخص') : 'نامشخص');
                                            $cityCount = is_array($city) ? ($city['count'] ?? $city['location_count'] ?? 0) : (is_object($city) ? ($city->count ?? $city->location_count ?? 0) : 0);
                                            $cityPercentage = is_array($city) ? ($city['percentage'] ?? 0) : (is_object($city) ? ($city->percentage ?? 0) : 0);
                                            $cityGrowth = is_array($city) ? ($city['growth'] ?? $city['growth_rate'] ?? 0) : (is_object($city) ? ($city->growth ?? $city->growth_rate ?? 0) : 0);
                                        @endphp
                                        <tr>
                                            <td>
                                                <span class="rank-badge rank-{{ $index < 3 ? $index + 1 : 'other' }}">
                                                    {{ $index + 1 }}
                                                </span>
                                            </td>
                                            <td>
                                                <div class="city-info">
                                                    <strong>{{ $cityName }}</strong>
                                                </div>
                                            </td>
                                            <td>{{ $cityCount }}</td>
                                            <td>
                                                <div class="percentage-bar">
                                                    <span>{{ $cityPercentage }}%</span>
                                                    <div class="bar">
                                                        <div class="fill" style="width: {{ $cityPercentage }}%"></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="growth-indicator {{ $cityGrowth >= 0 ? 'positive' : 'negative' }}">
                                                    <i class="fas fa-{{ $cityGrowth >= 0 ? 'arrow-up' : 'arrow-down' }}"></i>
                                                    {{ $cityGrowth }}%
                                                </span>
                                            </td>
                                            <td>
                                                @php
                                                    $status = $cityCount > 50 ? 'عالی' : ($cityCount > 20 ? 'خوب' : 'متوسط');
                                                    $statusClass = $cityCount > 50 ? 'success' : ($cityCount > 20 ? 'warning' : 'secondary');
                                                @endphp
                                                <span class="badge bg-{{ $statusClass }}">{{ $status }}</span>
                                            </td>
                                        </tr>
                                        @endforeach
                                    @else
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">
                                                <i class="fas fa-info-circle me-2"></i>
                                                داده‌ای برای نمایش وجود ندارد
                                            </td>
                                        </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Villages Section -->
    @if(isset($villagesData) && count($villagesData) > 0)
    <div class="geo-view d-none" id="villages-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-home text-success 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="toggleVillageChart('bar')">
                                    <i class="fas fa-chart-bar"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleVillageChart('pie')">
                                    <i class="fas fa-chart-pie"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="villages-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="villages-ranking-card">
                    <div class="ranking-header">
                        <h6 class="mb-0">
                            <i class="fas fa-home text-success me-2"></i>
                            رتبه‌بندی روستاها
                        </h6>
                    </div>
                    <div class="ranking-body">
                        @foreach(array_slice($villagesData, 0, 10) as $index => $village)
                        <div class="ranking-item">
                            <div class="ranking-position">
                                <span class="position-number">{{ $index + 1 }}</span>
                            </div>
                            <div class="ranking-content">
                                <div class="ranking-name">{{ $village['name'] }}</div>
                                <div class="ranking-value">{{ $village['count'] }} مکان</div>
                                <div class="ranking-percentage">
                                    {{ round(($village['count'] / array_sum(array_column($villagesData, 'count'))) * 100, 1) }}%
                                </div>
                            </div>
                            <div class="ranking-bar">
                                <div class="bar-fill" style="width: {{ round(($village['count'] / max(array_column($villagesData, 'count'))) * 100, 1) }}%"></div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- Heatmap Section -->
    <div class="geo-view d-none" id="heatmap-view">
        <div class="row">
            <div class="col-lg-9 mb-4">
                <div class="geo-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-fire text-danger 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="toggleHeatmapIntensity('low')">
                                    کم
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleHeatmapIntensity('medium')">
                                    متوسط
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleHeatmapIntensity('high')">
                                    زیاد
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="heatmap-container" class="heatmap-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 mb-4">
                <div class="heatmap-legend-card">
                    <div class="legend-header">
                        <h6 class="mb-0">
                            <i class="fas fa-palette text-info me-2"></i>
                            راهنمای رنگ‌ها
                        </h6>
                    </div>
                    <div class="legend-body">
                        <div class="legend-item">
                            <div class="legend-color" style="background: #ff0000;"></div>
                            <div class="legend-text">
                                <strong>بسیار زیاد</strong>
                                <span>بیش از 100 مکان</span>
                            </div>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #ff8000;"></div>
                            <div class="legend-text">
                                <strong>زیاد</strong>
                                <span>50-100 مکان</span>
                            </div>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #ffff00;"></div>
                            <div class="legend-text">
                                <strong>متوسط</strong>
                                <span>20-50 مکان</span>
                            </div>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #80ff00;"></div>
                            <div class="legend-text">
                                <strong>کم</strong>
                                <span>5-20 مکان</span>
                            </div>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #0080ff;"></div>
                            <div class="legend-text">
                                <strong>بسیار کم</strong>
                                <span>کمتر از 5 مکان</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Geographic Insights -->
    <div class="row">
        <div class="col-lg-6 mb-4">
            <div class="geo-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">
                    @if(isset($geographicInsights) && count($geographicInsights) > 0)
                        @foreach($geographicInsights as $insight)
                        <div class="insight-item insight-{{ $insight['type'] }}">
                            <div class="insight-icon">
                                <i class="fas fa-{{ $insight['icon'] }}"></i>
                            </div>
                            <div class="insight-content">
                                <div class="insight-title">{{ $insight['title'] }}</div>
                                <div class="insight-message">{{ $insight['message'] }}</div>
                            </div>
                        </div>
                        @endforeach
                    @else
                        <div class="insight-item insight-info">
                            <div class="insight-icon">
                                <i class="fas fa-info-circle"></i>
                            </div>
                            <div class="insight-content">
                                <div class="insight-title">در حال تحلیل</div>
                                <div class="insight-message">بینش‌های جغرافیایی در حال محاسبه هستند</div>
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-4">
            <div class="geo-trends-card">
                <div class="trends-header">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-area text-primary me-2"></i>
                        روندهای جغرافیایی
                    </h6>
                </div>
                <div class="trends-body">
                    <div id="geographic-trends-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('styles')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    /* Modern Geographic Analytics Styles */
    .geographic-analytics-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .geographic-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="geographic" width="40" height="40" patternUnits="userSpaceOnUse"><rect width="40" height="40" fill="none"/><circle cx="20" cy="20" r="3" fill="white" opacity="0.1"/><path d="M10,10 L30,10 L30,30 L10,30 Z" fill="none" stroke="white" stroke-width="0.5" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23geographic)"/></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);
    }

    /* Enhanced Geographic KPI Cards */
    .geo-kpi-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%;
        position: relative;
        overflow: hidden;
    }

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

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

    .geo-kpi-card .card-icon {
        width: 60px;
        height: 60px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;
        margin-bottom: 1rem;
        position: relative;
        z-index: 1;
    }

    .geo-kpi-card .card-content {
        position: relative;
        z-index: 1;
    }

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

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

    .geo-kpi-card .card-trend {
        font-size: 0.8rem;
        font-weight: 500;
        display: flex;
        align-items: center;
        margin-bottom: 1rem;
    }

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

    .geo-kpi-card .card-trend.negative {
        color: #dc3545;
    }

    .geo-kpi-card .card-trend.neutral {
        color: #6c757d;
    }

    .geo-kpi-card .card-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: #f0f0f0;
    }

    .geo-kpi-card .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        transition: width 0.3s ease;
    }

    /* Chart Cards */
    .geo-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: 400px;
        position: relative;
    }

    .map-container {
        height: 500px;
        border-radius: 12px;
        overflow: hidden;
        position: relative;
    }

    .heatmap-container {
        height: 600px;
        border-radius: 12px;
        overflow: hidden;
        position: relative;
    }

    /* Summary Card */
    .geo-summary-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%;
    }

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

    .summary-body {
        padding: 1.5rem;
    }

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

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

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

    .summary-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.2rem;
        flex-shrink: 0;
    }

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

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

    .summary-detail {
        font-size: 0.8rem;
        color: #28a745;
        font-weight: 500;
    }

    /* Provinces Ranking Card */
    .provinces-ranking-card, .villages-ranking-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%;
    }

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

    .ranking-body {
        padding: 1.5rem;
        max-height: 500px;
        overflow-y: auto;
    }

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

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

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

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

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

    .ranking-value {
        font-size: 0.9rem;
        color: #6c757d;
        margin-bottom: 0.25rem;
    }

    .ranking-percentage {
        font-size: 0.8rem;
        color: #28a745;
        font-weight: 500;
    }

    .ranking-bar {
        flex: 1;
        height: 6px;
        background: #e9ecef;
        border-radius: 3px;
        overflow: hidden;
        margin-left: 1rem;
    }

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

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

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

    .table-body {
        padding: 1.5rem;
    }

    .table-responsive {
        border-radius: 8px;
        overflow: hidden;
    }

    .table {
        margin-bottom: 0;
    }

    .table th {
        background: #f8f9fa;
        border: none;
        font-weight: 600;
        color: #2c3e50;
        padding: 1rem;
    }

    .table td {
        border: none;
        padding: 1rem;
        vertical-align: middle;
    }

    .table tbody tr:hover {
        background: #f8f9fa;
    }

    .rank-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        font-weight: 700;
        font-size: 0.8rem;
    }

    .rank-badge.rank-1 {
        background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
        color: #8b5a00;
    }

    .rank-badge.rank-2 {
        background: linear-gradient(135deg, #c0c0c0 0%, #e5e5e5 100%);
        color: #666;
    }

    .rank-badge.rank-3 {
        background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
        color: #fff;
    }

    .rank-badge.rank-other {
        background: #f8f9fa;
        color: #6c757d;
    }

    .percentage-bar {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .percentage-bar .bar {
        flex: 1;
        height: 6px;
        background: #e9ecef;
        border-radius: 3px;
        overflow: hidden;
    }

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

    .growth-indicator {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        font-weight: 500;
    }

    .growth-indicator.positive {
        color: #28a745;
    }

    .growth-indicator.negative {
        color: #dc3545;
    }

    /* Heatmap Legend Card */
    .heatmap-legend-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%;
    }

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

    .legend-body {
        padding: 1.5rem;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
        padding: 0.75rem;
        background: #f8f9fa;
        border-radius: 8px;
    }

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

    .legend-color {
        width: 20px;
        height: 20px;
        border-radius: 4px;
        flex-shrink: 0;
    }

    .legend-text strong {
        display: block;
        color: #2c3e50;
        font-size: 0.9rem;
        margin-bottom: 0.25rem;
    }

    .legend-text span {
        color: #6c757d;
        font-size: 0.8rem;
    }

    /* Insights and Trends Cards */
    .geo-insights-card, .geo-trends-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, .trends-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
    }

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

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

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

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

    .insight-item.insight-success {
        background: #d4edda;
        border-left: 4px solid #28a745;
    }

    .insight-item.insight-info {
        background: #d1ecf1;
        border-left: 4px solid #17a2b8;
    }

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

    .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;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

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

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

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

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

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

    /* No Data State */
    .no-data {
        text-align: center;
        padding: 2rem;
        color: #6c757d;
    }

    .no-data i {
        font-size: 3rem;
        margin-bottom: 1rem;
    }

    /* 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;
        }

        .geo-kpi-card {
            text-align: center;
        }

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

        .summary-item, .ranking-item {
            flex-direction: column;
            text-align: center;
        }

        .ranking-bar {
            margin-left: 0;
            margin-top: 0.5rem;
        }
    }
</style>
@endsection

@section('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.heat@0.2.0/dist/leaflet-heat.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@latest"></script>
<script>
// Geographic Analytics Script - Isolated
(function() {
    'use strict';

    // Prevent conflicts with other analytics scripts
    if (window.geographicAnalyticsLoaded) {
        return;
    }
    window.geographicAnalyticsLoaded = true;

document.addEventListener('DOMContentLoaded', function() {
    // Geographic data from backend
    const mapData = @json($mapData ?? []);
    const regionData = @json($regionData ?? []);
    const cityPerformance = @json($cityPerformance ?? []);
    const populationDensity = @json($populationDensity ?? []);
    const urbanRuralData = @json($urbanRuralData ?? []);
    const geographicTrends = @json($geographicTrends ?? ['labels' => [], 'series' => []]);
    const villagesData = @json($villagesData ?? []);
    const heatmapData = @json($heatmapData ?? []);

    // Initialize the page
    initGeographicAnalytics();

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

        // Initialize charts and maps
        initIranInteractiveMap();
        initProvincesChart();
        initCitiesChart();
        initPopulationDensityChart();
        if (villagesData && villagesData.length > 0) {
            initVillagesChart();
        }
        initHeatmapView();
        initGeographicTrendsChart();

        // Initialize real-time updates
        initGeoRealTimeUpdates();
    }

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

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

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

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

            // Initialize specific view components
            if (viewType === 'heatmap') {
                setTimeout(() => initHeatmapView(), 100);
            }
        }
    }

    function initIranInteractiveMap() {
        const mapContainer = document.getElementById('iran-interactive-map');
        if (!mapContainer) return;

        // Initialize Leaflet map centered on Iran
        const map = L.map('iran-interactive-map').setView([32.4279, 53.6880], 6);

        // Add tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);

        // Add markers for provinces
        if (mapData && mapData.length > 0) {
            console.log('Adding markers for mapData:', mapData);
            mapData.forEach(province => {
                const lat = parseFloat(province.lat || province.latitude);
                const lng = parseFloat(province.lng || province.longitude);

                if (lat && lng && !isNaN(lat) && !isNaN(lng)) {
                    const marker = L.marker([lat, lng])
                        .bindPopup(`
                            <div class="map-popup">
                                <h6>${province.name || 'نامشخص'}</h6>
                                <p>تعداد مکان‌ها: ${province.count || 0}</p>
                                <p>درصد: ${province.percentage || 0}%</p>
                                <p>مختصات: ${lat.toFixed(4)}, ${lng.toFixed(4)}</p>
                            </div>
                        `)
                        .addTo(map);
                    console.log(`Added marker for ${province.name} at [${lat}, ${lng}]`);
                } else {
                    console.log(`Invalid coordinates for ${province.name}: lat=${lat}, lng=${lng}`);
                }
            });
        } else {
            console.log('No mapData available, adding sample markers');

            // Add sample markers for major Iranian cities
            const sampleMarkers = [
                {name: 'تهران', lat: 35.6892, lng: 51.3890, count: 150, percentage: 25},
                {name: 'مشهد', lat: 36.2972, lng: 59.6067, count: 80, percentage: 15},
                {name: 'اصفهان', lat: 32.6539, lng: 51.6660, count: 60, percentage: 12},
                {name: 'شیراز', lat: 29.5926, lng: 52.5836, count: 45, percentage: 10},
                {name: 'تبریز', lat: 38.0962, lng: 46.2738, count: 35, percentage: 8}
            ];

            sampleMarkers.forEach(city => {
                L.marker([city.lat, city.lng])
                    .bindPopup(`
                        <div class="map-popup">
                            <h6>${city.name}</h6>
                            <p>تعداد مکان‌ها: ${city.count}</p>
                            <p>درصد: ${city.percentage}%</p>
                        </div>
                    `)
                    .addTo(map);
            });
        }

        window.iranMap = map;
    }

    function initProvincesChart() {
        if (!regionData || regionData.length === 0) return;

        const labels = regionData.slice(0, 10).map(item => item.name);
        const data = regionData.slice(0, 10).map(item => item.count);

        const options = {
            series: [{
                name: 'تعداد مکان‌ها',
                data: data
            }],
            chart: {
                type: 'bar',
                height: 400,
                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']
            },
            xaxis: {
                categories: labels,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد مکان‌ها',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                opacity: 1,
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: ['#764ba2'],
                    inverseColors: true,
                    opacityFrom: 1,
                    opacityTo: 1,
                    stops: [0, 100]
                }
            },
            colors: ['#667eea'],
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مکان";
                    }
                }
            }
        };

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

    function initCitiesChart() {
        if (!cityPerformance || cityPerformance.length === 0) return;

        const labels = cityPerformance.slice(0, 8).map(item => item.name);
        const data = cityPerformance.slice(0, 8).map(item => item.count);

        const options = {
            series: data,
            chart: {
                type: 'donut',
                height: 400,
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            labels: labels,
            colors: ['#667eea', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6f42c1', '#fd7e14', '#20c997'],
            plotOptions: {
                pie: {
                    donut: {
                        size: '70%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'مجموع',
                                formatter: function (w) {
                                    return w.globals.seriesTotals.reduce((a, b) => {
                                        return a + b;
                                    }, 0);
                                }
                            }
                        }
                    }
                }
            },
            legend: {
                position: 'bottom',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مکان";
                    }
                }
            }
        };

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

    function initPopulationDensityChart() {
        if (!populationDensity || populationDensity.length === 0) {
            // Create sample data for demonstration
            const sampleData = [
                { name: 'تهران', population: 8500000, locations: 450 },
                { name: 'مشهد', population: 3200000, locations: 180 },
                { name: 'اصفهان', population: 2000000, locations: 120 },
                { name: 'شیراز', population: 1800000, locations: 95 },
                { name: 'تبریز', population: 1700000, locations: 85 }
            ];

            const options = {
                series: [{
                    name: 'تعداد مکان‌ها',
                    data: sampleData.map(item => ({
                        x: item.population / 1000000,
                        y: item.locations,
                        z: item.name
                    }))
                }],
                chart: {
                    height: 400,
                    type: 'scatter',
                    fontFamily: 'IRANSans, tahoma, sans-serif',
                    toolbar: {
                        show: false
                    }
                },
                xaxis: {
                    title: {
                        text: 'جمعیت (میلیون نفر)',
                        style: {
                            fontFamily: 'IRANSans, tahoma, sans-serif'
                        }
                    }
                },
                yaxis: {
                    title: {
                        text: 'تعداد مکان‌ها',
                        style: {
                            fontFamily: 'IRANSans, tahoma, sans-serif'
                        }
                    }
                },
                colors: ['#667eea'],
                tooltip: {
                    custom: function({series, seriesIndex, dataPointIndex, w}) {
                        const data = sampleData[dataPointIndex];
                        return `
                            <div class="custom-tooltip">
                                <strong>${data.name}</strong><br>
                                جمعیت: ${(data.population / 1000000).toFixed(1)} میلیون<br>
                                مکان‌ها: ${data.locations}
                            </div>
                        `;
                    }
                }
            };

            const chart = new ApexCharts(document.querySelector("#population-density-chart"), options);
            chart.render();
            window.populationChart = chart;
        }
    }

    function initHeatmapView() {
        const heatmapContainer = document.getElementById('heatmap-container');
        if (!heatmapContainer) return;

        // Initialize heatmap
        const heatmap = L.map('heatmap-container').setView([32.4279, 53.6880], 6);

        // Add tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(heatmap);

        // Use real heatmap data from backend
        const realHeatmapData = heatmapData && heatmapData.length > 0 ?
            heatmapData :
            [
                [35.6892, 51.3890, 0.9], // Tehran
                [36.2972, 59.6067, 0.7], // Mashhad
                [32.6539, 51.6660, 0.6], // Isfahan
                [29.5926, 52.5836, 0.5], // Shiraz
                [38.0962, 46.2738, 0.4], // Tabriz
                [31.3183, 48.6706, 0.3], // Ahvaz
                [36.5659, 53.0586, 0.3], // Sari
                [27.1865, 56.2808, 0.2], // Bandar Abbas
            ];

        // Add heatmap layer
        const heat = L.heatLayer(realHeatmapData, {
            radius: 50,
            blur: 25,
            maxZoom: 10,
            gradient: {
                0.0: '#0080ff',
                0.2: '#80ff00',
                0.4: '#ffff00',
                0.6: '#ff8000',
                0.8: '#ff0000',
                1.0: '#800000'
            }
        }).addTo(heatmap);

        window.heatmapMap = heatmap;
    }

    function initVillagesChart() {
        if (!villagesData || villagesData.length === 0) return;

        const labels = villagesData.slice(0, 10).map(item => item.name);
        const data = villagesData.slice(0, 10).map(item => item.count);

        const options = {
            series: [{
                name: 'تعداد مکان‌ها',
                data: data
            }],
            chart: {
                type: 'bar',
                height: 400,
                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']
            },
            xaxis: {
                categories: labels,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد مکان‌ها',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                opacity: 1,
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: ['#28a745'],
                    inverseColors: true,
                    opacityFrom: 1,
                    opacityTo: 1,
                    stops: [0, 100]
                }
            },
            colors: ['#20c997'],
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مکان";
                    }
                }
            }
        };

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

    function initGeographicTrendsChart() {
        console.log('Initializing geographic trends chart with data:', geographicTrends);

        // Use real trends data from backend
        let trendsData;

        if (geographicTrends && geographicTrends.labels && geographicTrends.series &&
            geographicTrends.labels.length > 0 && geographicTrends.series.length > 0) {
            trendsData = geographicTrends;
            console.log('Using real trends data:', trendsData);
        } else {
            // Fallback to sample data
            trendsData = {
                labels: ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور'],
                series: [
                    { name: 'تهران', data: [45, 52, 48, 61, 55, 67] },
                    { name: 'اصفهان', data: [25, 28, 22, 35, 30, 38] },
                    { name: 'شیراز', data: [18, 22, 19, 28, 24, 31] }
                ]
            };
            console.log('Using fallback trends data:', trendsData);
        }

        const options = {
            series: trendsData.series,
            chart: {
                height: 300,
                type: 'area',
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            xaxis: {
                categories: trendsData.labels,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد مکان‌ها',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    opacityFrom: 0.6,
                    opacityTo: 0.1
                }
            },
            colors: ['#667eea', '#28a745', '#ffc107'],
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " مکان";
                    }
                }
            }
        };

        const chartElement = document.querySelector("#geographic-trends-chart");
        if (chartElement) {
            const chart = new ApexCharts(chartElement, options);
            chart.render();
            window.trendsChart = chart;
            console.log('Geographic trends chart rendered successfully');
        } else {
            console.error('Geographic trends chart element not found');
        }
    }

    function initGeoRealTimeUpdates() {
        // Simulate real-time updates every 60 seconds
        setInterval(() => {
            updateGeoKPICards();
        }, 60000);
    }

    function updateGeoKPICards() {
        // Simulate small random changes in KPI values
        const cards = document.querySelectorAll('.geo-kpi-card .card-value');
        cards.forEach(card => {
            const currentValue = parseInt(card.textContent);
            const change = Math.floor(Math.random() * 3) - 1; // -1, 0, or 1
            const newValue = Math.max(0, currentValue + change);

            if (newValue !== currentValue) {
                card.style.transition = 'all 0.3s ease';
                card.textContent = newValue;
                card.style.transform = 'scale(1.1)';

                setTimeout(() => {
                    card.style.transform = 'scale(1)';
                }, 300);
            }
        });
    }

    // Global functions for external use
    window.toggleMapLayer = function(layer) {
        console.log('Toggling map layer:', layer);

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

        if (window.iranMap) {
            // Clear existing layers (except base tile layer)
            window.iranMap.eachLayer(function(mapLayer) {
                if (mapLayer instanceof L.Marker || mapLayer instanceof L.HeatLayer || mapLayer instanceof L.Circle) {
                    window.iranMap.removeLayer(mapLayer);
                }
            });

            if (layer === 'locations') {
                // Add location markers
                if (mapData && mapData.length > 0) {
                    mapData.forEach(province => {
                        if (province.lat && province.lng) {
                            L.marker([province.lat, province.lng])
                                .bindPopup(`
                                    <div class="map-popup">
                                        <h6>${province.name}</h6>
                                        <p>تعداد مکان‌ها: ${province.count}</p>
                                        <p>درصد: ${province.percentage}%</p>
                                    </div>
                                `)
                                .addTo(window.iranMap);
                        }
                    });
                }
            } else if (layer === 'heatmap') {
                // Add heatmap layer
                const realHeatmapData = heatmapData && heatmapData.length > 0 ? heatmapData : [
                    [35.6892, 51.3890, 0.9], [36.2972, 59.6067, 0.7], [32.6539, 51.6660, 0.6],
                    [29.5926, 52.5836, 0.5], [38.0962, 46.2738, 0.4], [31.3183, 48.6706, 0.3]
                ];

                console.log('Adding heatmap with data:', realHeatmapData);

                const heatLayer = L.heatLayer(realHeatmapData, {
                    radius: 40,
                    blur: 20,
                    maxZoom: 10,
                    gradient: {
                        0.0: '#0080ff',
                        0.2: '#80ff00',
                        0.4: '#ffff00',
                        0.6: '#ff8000',
                        0.8: '#ff0000',
                        1.0: '#800000'
                    }
                });

                heatLayer.addTo(window.iranMap);
                window.currentHeatLayer = heatLayer;
            } else if (layer === 'clusters') {
                // Add clustered markers
                console.log('Adding clusters with mapData:', mapData);

                if (mapData && mapData.length > 0) {
                    mapData.forEach(province => {
                        const lat = parseFloat(province.lat || province.latitude);
                        const lng = parseFloat(province.lng || province.longitude);
                        const count = parseInt(province.count || 0);

                        if (lat && lng && !isNaN(lat) && !isNaN(lng)) {
                            // Calculate circle size based on count
                            const baseSize = Math.max(5, Math.min(30, count));
                            const circleRadius = baseSize * 1000; // Convert to meters

                            // Create color based on count
                            const intensity = Math.min(1, count / 100);
                            const color = intensity > 0.7 ? '#dc3545' :
                                         intensity > 0.4 ? '#ffc107' :
                                         intensity > 0.2 ? '#28a745' : '#17a2b8';

                            const circle = L.circle([lat, lng], {
                                color: color,
                                fillColor: color,
                                fillOpacity: 0.6,
                                radius: circleRadius,
                                weight: 2
                            }).bindPopup(`
                                <div class="map-popup">
                                    <h6>${province.name || 'نامشخص'}</h6>
                                    <p>تعداد مکان‌ها: ${count}</p>
                                    <p>مختصات: ${lat.toFixed(4)}, ${lng.toFixed(4)}</p>
                                </div>
                            `);

                            circle.addTo(window.iranMap);

                            console.log(`Added circle for ${province.name} at [${lat}, ${lng}] with radius ${circleRadius}`);
                        } else {
                            console.log(`Invalid coordinates for ${province.name}: lat=${lat}, lng=${lng}`);
                        }
                    });
                } else {
                    console.log('No mapData available for clusters');

                    // Add sample clusters for major Iranian cities
                    const sampleClusters = [
                        {name: 'تهران', lat: 35.6892, lng: 51.3890, count: 150},
                        {name: 'مشهد', lat: 36.2972, lng: 59.6067, count: 80},
                        {name: 'اصفهان', lat: 32.6539, lng: 51.6660, count: 60},
                        {name: 'شیراز', lat: 29.5926, lng: 52.5836, count: 45},
                        {name: 'تبریز', lat: 38.0962, lng: 46.2738, count: 35}
                    ];

                    sampleClusters.forEach(city => {
                        const baseSize = Math.max(5, Math.min(30, city.count / 5));
                        const circleRadius = baseSize * 1000;

                        const intensity = Math.min(1, city.count / 150);
                        const color = intensity > 0.7 ? '#dc3545' :
                                     intensity > 0.4 ? '#ffc107' :
                                     intensity > 0.2 ? '#28a745' : '#17a2b8';

                        L.circle([city.lat, city.lng], {
                            color: color,
                            fillColor: color,
                            fillOpacity: 0.6,
                            radius: circleRadius,
                            weight: 2
                        }).bindPopup(`
                            <div class="map-popup">
                                <h6>${city.name}</h6>
                                <p>تعداد مکان‌ها: ${city.count}</p>
                            </div>
                        `).addTo(window.iranMap);
                    });
                }
            }
        }

        showNotification(`نمایش لایه ${layer}`, 'info');
    };

    window.toggleProvinceChart = function(type) {
        console.log('Toggling province chart to:', type);

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

        if (window.provincesChart) {
            // Here you would update the chart type
            showNotification(`تغییر نمودار به ${type}`, 'info');
        }
    };

    window.toggleVillageChart = function(type) {
        console.log('Toggling village chart to:', type);

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

        if (window.villagesChart) {
            showNotification(`تغییر نمودار روستاها به ${type}`, 'info');
        }
    };

    window.toggleHeatmapIntensity = function(intensity) {
        console.log('Toggling heatmap intensity to:', intensity);

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

        if (window.heatmapMap) {
            // Update heatmap intensity
            const intensityMultiplier = intensity === 'low' ? 0.5 : (intensity === 'medium' ? 1.0 : 1.5);

            // Remove existing heatmap layer
            window.heatmapMap.eachLayer(function(layer) {
                if (layer instanceof L.HeatLayer) {
                    window.heatmapMap.removeLayer(layer);
                }
            });

            // Add new heatmap with adjusted intensity
            const realHeatmapData = heatmapData && heatmapData.length > 0 ?
                heatmapData.map(point => [point[0], point[1], point[2] * intensityMultiplier]) :
                [
                    [35.6892, 51.3890, 0.9 * intensityMultiplier],
                    [36.2972, 59.6067, 0.7 * intensityMultiplier],
                    [32.6539, 51.6660, 0.6 * intensityMultiplier]
                ];

            L.heatLayer(realHeatmapData, {
                radius: 50,
                blur: 25,
                maxZoom: 10,
                gradient: {
                    0.0: '#0080ff',
                    0.2: '#80ff00',
                    0.4: '#ffff00',
                    0.6: '#ff8000',
                    0.8: '#ff0000',
                    1.0: '#800000'
                }
            }).addTo(window.heatmapMap);
        }

        showNotification(`تنظیم شدت نقشه حرارتی: ${intensity}`, 'info');
    };

    window.applyGeoFilter = function(days) {
        console.log('Applying geographic filter for', days, 'days');
        showNotification(`اعمال فیلتر ${days} روز گذشته...`, 'info');

        // Simulate filter application
        setTimeout(() => {
            showNotification('فیلتر اعمال شد', 'success');
            // Here you would reload the data
        }, 1500);
    };

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

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

    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);
    }
});

})(); // End of IIFE (Immediately Invoked Function Expression)
</script>
@endsection