@extends('admin.layouts.app')

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

@section('content')

<div x-data="analyticsData()" x-init="init()" class="space-y-6">
    
    <!-- Header with Controls -->
    <div class="card p-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
                <h2 class="text-xl font-bold text-primary">{{ admin_trans('analytics_dashboard') }}</h2>
                <p class="text-sm text-tertiary mt-1">{{ admin_trans('track_app_usage_and_user_behavior') }}</p>
            </div>
            
            <div class="flex flex-col sm:flex-row gap-3">
                <!-- Period Selector -->
                <select x-model="selectedPeriod" @change="loadStats()" class="input">
                    <option value="today">{{ admin_trans('today') }}</option>
                    <option value="yesterday">{{ admin_trans('yesterday') }}</option>
                    <option value="last_7_days">{{ admin_trans('last_7_days') }}</option>
                    <option value="last_30_days">{{ admin_trans('last_30_days') }}</option>
                </select>
                
                <!-- Refresh Button -->
                <button @click="loadStats()" :disabled="loading" class="btn btn-secondary">
                    <i data-lucide="refresh-cw" class="w-4 h-4" :class="loading ? 'animate-spin' : ''"></i>
                    <span class="hidden sm:inline">{{ admin_trans('refresh') }}</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Real-time Stats -->
    <div class="card p-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-primary">{{ admin_trans('real_time_activity') }}</h3>
            <span class="flex items-center gap-2 text-sm text-tertiary">
                <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
                {{ admin_trans('live') }}
            </span>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="stats-card">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-green-100 flex items-center justify-center">
                        <i data-lucide="users" class="w-5 h-5 text-green-600"></i>
                    </div>
                    <div>
                        <div class="text-2xl font-bold text-primary" x-text="realTimeStats.active_sessions_estimate || '0'"></div>
                        <div class="text-sm text-tertiary">{{ admin_trans('active_sessions') }}</div>
                    </div>
                </div>
            </div>
            
            <div class="stats-card">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center">
                        <i data-lucide="eye" class="w-5 h-5 text-blue-600"></i>
                    </div>
                    <div>
                        <div class="text-2xl font-bold text-primary" x-text="realTimeStats.page_views_last_hour || '0'"></div>
                        <div class="text-sm text-tertiary">{{ admin_trans('views_last_hour') }}</div>
                    </div>
                </div>
            </div>
            
            <div class="stats-card">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center">
                        <i data-lucide="zap" class="w-5 h-5 text-purple-600"></i>
                    </div>
                    <div>
                        <div class="text-2xl font-bold text-primary" x-text="realTimeStats.events_last_hour || '0'"></div>
                        <div class="text-sm text-tertiary">{{ admin_trans('events_last_hour') }}</div>
                    </div>
                </div>
            </div>
            
            <div class="stats-card">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-orange-100 flex items-center justify-center">
                        <i data-lucide="activity" class="w-5 h-5 text-orange-600"></i>
                    </div>
                    <div>
                        <div class="text-2xl font-bold text-primary" x-text="stats.pages_per_session || '0'"></div>
                        <div class="text-sm text-tertiary">{{ admin_trans('pages_per_session') }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overview Stats -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <x-stat-card 
            :title="admin_trans('total_page_views')"
            icon="eye"
            color="blue"
            x-text="stats.total_page_views || '0'"
        />
        
        <x-stat-card 
            :title="admin_trans('total_sessions')"
            icon="users"
            color="green"
            x-text="stats.total_sessions || '0'"
        />
        
        <x-stat-card 
            :title="admin_trans('total_events')"
            icon="zap"
            color="purple"
            x-text="stats.total_events || '0'"
        />
        
        <x-stat-card 
            :title="admin_trans('unique_sessions')"
            icon="user-check"
            color="orange"
            x-text="stats.unique_sessions || '0'"
        />
    </div>

    <!-- Charts Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Platform Stats -->
        <div class="card p-6">
            <h3 class="text-lg font-semibold text-primary mb-4">{{ admin_trans('platform_breakdown') }}</h3>
            <div class="space-y-3">
                <template x-for="(stats, platform) in platformStats" :key="platform">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <div class="w-8 h-8 rounded-lg bg-primary-light flex items-center justify-center">
                                <i x-bind:data-lucide="platform === 'android' ? 'smartphone' : platform === 'ios' ? 'smartphone' : 'monitor'" class="w-4 h-4 text-primary"></i>
                            </div>
                            <span class="font-medium text-primary capitalize" x-text="platform"></span>
                        </div>
                        <div class="text-right">
                            <div class="font-semibold text-primary" x-text="stats.count"></div>
                            <div class="text-sm text-tertiary" x-text="stats.percentage + '%'"></div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Hourly Activity (if today/yesterday) -->
        <div x-show="selectedPeriod === 'today' || selectedPeriod === 'yesterday'" class="card p-6">
            <h3 class="text-lg font-semibold text-primary mb-4">{{ admin_trans('hourly_activity') }}</h3>
            <div class="h-48 flex items-end justify-between gap-1">
                <template x-for="hour in hourlyActivity" :key="hour.hour">
                    <div class="flex-1 flex flex-col items-center">
                        <div class="bg-primary rounded-t-sm transition-all duration-300" 
                             :style="`height: ${Math.max((hour.views / maxHourlyViews) * 100, 2)}%`"
                             :title="`${hour.hour}:00 - ${hour.views} views`"></div>
                        <span class="text-xs text-tertiary mt-1" x-text="hour.hour"></span>
                    </div>
                </template>
            </div>
        </div>

        <!-- Top Events (if not hourly view) -->
        <div x-show="selectedPeriod !== 'today' && selectedPeriod !== 'yesterday'" class="card p-6">
            <h3 class="text-lg font-semibold text-primary mb-4">{{ admin_trans('top_events') }}</h3>
            <div class="space-y-3">
                <template x-for="event in topEvents.slice(0, 5)" :key="event.event_name">
                    <div class="flex items-center justify-between py-2">
                        <div>
                            <div class="font-medium text-primary" x-text="event.event_name"></div>
                            <div class="text-sm text-tertiary" x-text="`${event.unique_users} unique users`"></div>
                        </div>
                        <div class="text-lg font-bold text-primary" x-text="event.count"></div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- Top Pages -->
    <div class="card p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-semibold text-primary">{{ admin_trans('top_pages') }}</h3>
            <span class="text-sm text-tertiary" x-text="`${selectedPeriod} data`"></span>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead>
                    <tr class="border-b border-border">
                        <th class="text-left py-3 px-4 font-semibold text-secondary">{{ admin_trans('page') }}</th>
                        <th class="text-right py-3 px-4 font-semibold text-secondary">{{ admin_trans('views') }}</th>
                        <th class="text-right py-3 px-4 font-semibold text-secondary">{{ admin_trans('sessions') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="page in topPages.slice(0, 10)" :key="page.url">
                        <tr class="border-b border-border hover:bg-bg-secondary">
                            <td class="py-3 px-4">
                                <div>
                                    <div class="font-medium text-primary" x-text="page.title || page.url"></div>
                                    <div class="text-sm text-tertiary" x-text="page.url"></div>
                                </div>
                            </td>
                            <td class="py-3 px-4 text-right">
                                <span class="font-semibold text-primary" x-text="page.views"></span>
                            </td>
                            <td class="py-3 px-4 text-right">
                                <span class="font-medium text-secondary" x-text="page.unique_sessions"></span>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Loading State -->
    <div x-show="loading" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-xl p-6 flex items-center gap-3">
            <div class="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
            <span class="font-medium">{{ admin_trans('loading_analytics') }}...</span>
        </div>
    </div>

</div>

@endsection

@push('scripts')
<script>
function analyticsData() {
    return {
        loading: false,
        selectedPeriod: 'today',
        stats: {},
        realTimeStats: {},
        platformStats: {},
        topPages: [],
        topEvents: [],
        hourlyActivity: [],
        maxHourlyViews: 1,

        init() {
            this.loadStats();
            this.loadRealTimeStats();
            
            // Auto-refresh real-time stats every 30 seconds
            setInterval(() => {
                this.loadRealTimeStats();
            }, 30000);
        },

        async loadStats() {
            this.loading = true;
            
            try {
                const response = await fetch(`/admin/analytics/stats?period=${this.selectedPeriod}`, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });

                const data = await response.json();
                
                if (data.success) {
                    this.stats = data.data.stats;
                    this.platformStats = data.data.platform_stats;
                    this.topPages = data.data.top_pages;
                    this.topEvents = data.data.top_events;
                    this.hourlyActivity = data.data.hourly_activity || [];
                    
                    // Calculate max for hourly chart
                    if (this.hourlyActivity.length > 0) {
                        this.maxHourlyViews = Math.max(...this.hourlyActivity.map(h => h.views)) || 1;
                    }
                } else {
                    toast.error(data.message || 'Failed to load analytics');
                }
            } catch (error) {
                console.error('Analytics loading error:', error);
                toast.error('Error loading analytics data');
            } finally {
                this.loading = false;
            }
        },

        async loadRealTimeStats() {
            try {
                const response = await fetch('/admin/analytics/real-time-stats', {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });

                const data = await response.json();
                
                if (data.success) {
                    this.realTimeStats = data.data;
                }
            } catch (error) {
                console.error('Real-time stats error:', error);
            }
        }
    }
}
</script>
@endpush

<style>
.stats-card {
    @apply p-4 rounded-xl;
    background: var(--color-bg-primary);
    border: 1px solid var(--color-border);
}

.stats-card:hover {
    @apply shadow-lg;
    border-color: var(--color-primary);
}
</style>