@extends('admin.layouts.app')

@section('title', admin_trans('dashboard'))
@section('page-title', admin_trans('dashboard'))

@section('content')

<div x-data="dashboardData()" class="space-y-6">

    <!-- Main Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        
        <!-- Total Users -->
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('total_users') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary">{{ number_format($stats['total_users']) }}</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center gradient-primary shadow-lg">
                    <i data-lucide="users" class="w-7 h-7 text-white"></i>
                </div>
            </div>
            <div class="mt-4 flex items-center gap-2">
                @php
                    $growth = $stats['users_growth'];
                    $variant = $growth >= 0 ? 'success' : 'danger';
                    $icon = $growth >= 0 ? 'trending-up' : 'trending-down';
                @endphp
                <x-badge variant="{{ $variant }}" icon="{{ $icon }}">{{ abs($growth) }}%</x-badge>
                <span class="text-xs text-tertiary">{{ admin_trans('vs_last_month') }}</span>
            </div>
        </div>

        <!-- Total Stores -->
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('total_stores') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary">{{ number_format($stats['total_stores']) }}</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center gradient-secondary shadow-lg">
                    <i data-lucide="store" class="w-7 h-7 text-white"></i>
                </div>
            </div>
            <div class="mt-4 flex items-center gap-2">
                @php
                    $growth = $stats['stores_growth'];
                    $variant = $growth >= 0 ? 'success' : 'danger';
                    $icon = $growth >= 0 ? 'trending-up' : 'trending-down';
                @endphp
                <x-badge variant="{{ $variant }}" icon="{{ $icon }}">{{ abs($growth) }}%</x-badge>
                <span class="text-xs text-tertiary">{{ admin_trans('vs_last_month') }}</span>
            </div>
        </div>

        <!-- Total Offers -->
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('total_offers') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary">{{ number_format($stats['total_offers']) }}</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center shadow-lg" 
                     style="background: linear-gradient(135deg, #16CC62 0%, #0EA54E 100%);">
                    <i data-lucide="tag" class="w-7 h-7 text-white"></i>
                </div>
            </div>
            <div class="mt-4 flex items-center gap-2">
                @php
                    $growth = $stats['offers_growth'];
                    $variant = $growth >= 0 ? 'success' : 'danger';
                    $icon = $growth >= 0 ? 'trending-up' : 'trending-down';
                @endphp
                <x-badge variant="{{ $variant }}" icon="{{ $icon }}">{{ abs($growth) }}%</x-badge>
                <span class="text-xs text-tertiary">{{ admin_trans('vs_last_month') }}</span>
            </div>
        </div>

        <!-- Active Offers -->
        <div class="card hover:shadow-xl transition-all hover:-translate-y-1">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-secondary">{{ admin_trans('active_offers') }}</p>
                    <h3 class="text-3xl font-bold mt-2 text-primary">{{ number_format($stats['active_offers']) }}</h3>
                </div>
                <div class="w-14 h-14 rounded-xl flex items-center justify-center shadow-lg" 
                     style="background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);">
                    <i data-lucide="sparkles" class="w-7 h-7 text-white"></i>
                </div>
            </div>
            <div class="mt-4 flex items-center gap-2">
                @php
                    $growth = $stats['active_offers_growth'];
                    $variant = $growth >= 0 ? 'success' : 'danger';
                    $icon = $growth >= 0 ? 'trending-up' : 'trending-down';
                @endphp
                <x-badge variant="{{ $variant }}" icon="{{ $icon }}">{{ abs($growth) }}%</x-badge>
                <span class="text-xs text-tertiary">{{ admin_trans('vs_last_month') }}</span>
            </div>
        </div>

    </div>

    <!-- Quick Actions & Alerts -->
    @if(!empty($quickActions))
    <div class="card">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-bold flex items-center gap-2 text-primary">
                <i data-lucide="zap" class="w-5 h-5"></i>
                {{ admin_trans('quick_actions') }}
            </h2>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            @foreach($quickActions as $action)
                <a href="{{ $action['url'] }}" 
                   class="p-4 rounded-xl border transition-all hover:shadow-md hover:-translate-y-1"
                   style="border-color: var(--color-border); background: var(--color-bg-primary);"
                   onmouseover="this.style.borderColor='var(--color-{{ $action['color'] }})'"
                   onmouseout="this.style.borderColor='var(--color-border)'">
                    
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-lg flex items-center justify-center" 
                             style="background: var(--color-{{ $action['color'] }}-50);">
                            <i data-lucide="{{ $action['icon'] }}" class="w-5 h-5" 
                               style="color: var(--color-{{ $action['color'] }}-500);"></i>
                        </div>
                        <div class="flex-1">
                            <h4 class="font-semibold text-sm text-primary">{{ $action['title'] }}</h4>
                            <p class="text-xs text-secondary mt-1">{{ $action['description'] }}</p>
                        </div>
                        <x-badge variant="{{ $action['color'] }}">{{ $action['count'] }}</x-badge>
                    </div>
                </a>
            @endforeach
        </div>
    </div>
    @endif

    <!-- Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        <!-- Users Chart -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-primary">{{ admin_trans('users_chart_title') }}</h3>
                <x-badge variant="info">{{ number_format($chartsData['users']['total']) }}</x-badge>
            </div>
            <div class="h-64">
                <canvas id="usersChart"></canvas>
            </div>
        </div>

        <!-- Offers Chart -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-primary">{{ admin_trans('offers_chart_title') }}</h3>
                <x-badge variant="success">{{ number_format($chartsData['offers']['total']) }}</x-badge>
            </div>
            <div class="h-64">
                <canvas id="offersChart"></canvas>
            </div>
        </div>

        <!-- Categories Chart -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-primary">{{ admin_trans('categories_chart_title') }}</h3>
            </div>
            <div class="h-64">
                <canvas id="categoriesChart"></canvas>
            </div>
        </div>

        <!-- Activity Chart -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-primary">{{ admin_trans('activity_chart_title') }}</h3>
            </div>
            <div class="h-64">
                <canvas id="activityChart"></canvas>
            </div>
        </div>

    </div>

    <!-- Bottom Section -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Recent Activity -->
        <div class="lg:col-span-2 card">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-lg font-bold flex items-center gap-2 text-primary">
                    <i data-lucide="activity" class="w-5 h-5"></i>
                    {{ admin_trans('recent_activity') }}
                </h2>
                <x-button variant="ghost" size="sm" icon="arrow-right" iconPosition="right">
                    {{ admin_trans('view_all') }}
                </x-button>
            </div>

            <div class="space-y-3 max-h-96 overflow-y-auto">
                @forelse($recentActivities as $activity)
                <a href="{{ $activity['url'] }}" 
                   class="flex items-start gap-4 p-4 rounded-xl transition-all cursor-pointer hover:bg-primary-light block">
                    <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" 
                         style="background: {{ $activity['color'] === 'blue' ? 'var(--color-secondary-light)' : ($activity['color'] === 'green' ? 'var(--color-primary-light)' : ($activity['color'] === 'purple' ? 'rgba(139, 92, 246, 0.1)' : 'rgba(251, 191, 36, 0.1)')) }};">
                        <i data-lucide="{{ $activity['icon'] }}" class="w-5 h-5" 
                           style="color: {{ $activity['color'] === 'blue' ? 'var(--color-secondary)' : ($activity['color'] === 'green' ? 'var(--color-primary)' : ($activity['color'] === 'purple' ? '#8B5CF6' : '#FBBF24')) }};"></i>
                    </div>
                    <div class="flex-1">
                        <h4 class="font-semibold text-sm mb-1 text-primary">{{ $activity['title'] }}</h4>
                        <p class="text-sm text-secondary">{{ $activity['description'] }}</p>
                        <p class="text-xs mt-1.5 flex items-center gap-1 text-tertiary">
                            <i data-lucide="clock" class="w-3 h-3"></i>
                            {{ $activity['time'] }}
                        </p>
                    </div>
                </a>
                @empty
                    <x-empty-state
                        icon="activity"
                        title="{{ admin_trans('no_data') }}"
                        description="{{ admin_trans('no_recent_activities') }}"
                    />
                @endforelse
            </div>
        </div>

        <!-- Top Performers -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-lg font-bold flex items-center gap-2 text-primary">
                    <i data-lucide="trophy" class="w-5 h-5"></i>
                    {{ admin_trans('top_stores') }}
                </h2>
            </div>

            <div class="space-y-4">
                @forelse($topPerformers['stores'] as $index => $store)
                    @php
                        $storeName = $store->translations->first()->name ?? admin_trans('store');
                        $rankColors = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
                    @endphp
                    <div class="flex items-center gap-3 p-3 rounded-lg hover:bg-primary-light transition-colors">
                        <span class="text-lg">{{ $rankColors[$index] ?? ($index + 1) }}</span>
                        <div class="flex-1">
                            <h4 class="font-semibold text-sm text-primary">{{ $storeName }}</h4>
                            <p class="text-xs text-tertiary">{{ $store->offers_count }} {{ admin_trans('offers') }}</p>
                        </div>
                        <x-badge variant="primary">{{ $store->offers_count }}</x-badge>
                    </div>
                @empty
                    <div class="text-center py-4">
                        <p class="text-sm text-tertiary">{{ admin_trans('no_data') }}</p>
                    </div>
                @endforelse
            </div>

            <!-- Quick Stats -->
            <div class="mt-6 pt-4 border-t grid grid-cols-2 gap-4" style="border-color: var(--color-border);">
                <div class="text-center">
                    <p class="text-2xl font-bold text-primary">{{ number_format($stats['total_subscriptions']) }}</p>
                    <p class="text-xs text-tertiary">{{ admin_trans('total_subscriptions') }}</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-primary">{{ number_format($stats['expiring_soon_offers']) }}</p>
                    <p class="text-xs text-tertiary">{{ admin_trans('expiring_soon_offers') }}</p>
                </div>
            </div>
        </div>

    </div>

</div>

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function dashboardData() {
    return {
        chartsData: @json($chartsData),
        
        init() {
            this.$nextTick(() => {
                this.initCharts();
            });
        },

        initCharts() {
            // Users Chart
            this.createLineChart('usersChart', {
                labels: this.chartsData.users.labels,
                data: this.chartsData.users.data,
                label: '{{ admin_trans("users") }}',
                color: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)'
            });

            // Offers Chart
            this.createLineChart('offersChart', {
                labels: this.chartsData.offers.labels,
                data: this.chartsData.offers.data,
                label: '{{ admin_trans("offers") }}',
                color: 'rgb(22, 204, 98)',
                backgroundColor: 'rgba(22, 204, 98, 0.1)'
            });

            // Categories Chart
            this.createDoughnutChart('categoriesChart', {
                labels: this.chartsData.categories.labels,
                data: this.chartsData.categories.data
            });

            // Activity Chart
            this.createMultiLineChart('activityChart', this.chartsData.activity);
        },

        createLineChart(canvasId, config) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: config.labels,
                    datasets: [{
                        label: config.label,
                        data: config.data,
                        borderColor: config.color,
                        backgroundColor: config.backgroundColor,
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: config.color,
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            borderColor: config.color,
                            borderWidth: 1,
                            cornerRadius: 8,
                            displayColors: false
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#64748B',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            },
                            ticks: {
                                color: '#64748B',
                                font: {
                                    size: 12
                                }
                            }
                        }
                    }
                }
            });
        },

        createDoughnutChart(canvasId, config) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            const colors = [
                '#3B82F6', '#16CC62', '#F59E0B', '#EF4444', 
                '#8B5CF6', '#06B6D4', '#84CC16', '#F97316'
            ];

            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: config.labels,
                    datasets: [{
                        data: config.data,
                        backgroundColor: colors.slice(0, config.data.length),
                        borderWidth: 0,
                        hoverBorderWidth: 3,
                        hoverBorderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '60%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                usePointStyle: true,
                                pointStyle: 'circle',
                                padding: 20,
                                color: '#475569',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            cornerRadius: 8,
                            displayColors: true
                        }
                    }
                }
            });
        },

        createMultiLineChart(canvasId, config) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            const datasets = config.datasets.map(dataset => ({
                label: dataset.label,
                data: dataset.data,
                borderColor: dataset.color,
                backgroundColor: dataset.color + '20',
                borderWidth: 3,
                fill: false,
                tension: 0.4,
                pointBackgroundColor: dataset.color,
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6
            }));

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: config.labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                pointStyle: 'circle',
                                padding: 20,
                                color: '#475569',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            cornerRadius: 8,
                            displayColors: true
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#64748B',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            },
                            ticks: {
                                color: '#64748B',
                                font: {
                                    size: 12
                                }
                            }
                        }
                    }
                }
            });
        }
    }
}

// Auto refresh dashboard data every 5 minutes
setInterval(() => {
    // Optionally refresh data via AJAX
    console.log('Dashboard data refresh interval');
}, 300000);
</script>
@endpush