@extends('admin.layouts.app')

@section('title', 'Banner Campaigns')

@section('content')
<div class="container-fluid px-4 py-4" style="background: #f8f9fc;">
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-extrabold text-gray-900 tracking-tight" style="font-family: 'Nunito', sans-serif;">Banner Campaigns</h1>
            <p class="text-gray-500 font-medium mt-1">Manage your promotional assets with precision.</p>
        </div>
        <div class="flex gap-4">
            <a href="{{ route('admin.banners.analytics') }}" 
               class="flex items-center px-6 py-2.5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white font-bold shadow-lg shadow-indigo-200 transform hover:-translate-y-0.5 hover:shadow-xl transition-all duration-200 group">
                <i class="fas fa-chart-pie mr-2 text-indigo-200 group-hover:text-white transition-colors"></i> Analytics
            </a>
            <a href="{{ route('admin.banners.create') }}" 
               class="flex items-center px-6 py-2.5 rounded-full bg-gradient-to-r from-blue-600 to-cyan-500 text-white font-bold shadow-lg shadow-blue-200 transform hover:-translate-y-0.5 hover:shadow-xl transition-all duration-200 group">
                <i class="fas fa-plus mr-2 text-blue-100 group-hover:text-white transition-colors"></i> Create Campaign
            </a>
        </div>
    </div>

    <!-- Stats Tiles (5 Columns) -->
    <div class="grid grid-cols-1 md:grid-cols-5 gap-6 mb-8">
        <!-- Revenue Tile -->
        <div class="card border-0 shadow-sm rounded-xl bg-gradient-to-br from-indigo-600 to-violet-600 text-white transform hover:-translate-y-1 transition-all duration-300">
            <div class="card-body p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="text-xs font-bold uppercase text-indigo-100 tracking-wider">Total Revenue</div>
                    <div class="p-2 bg-white/20 rounded-lg backdrop-blur-sm">
                        <i class="fas fa-rupee-sign text-white"></i>
                    </div>
                </div>
                <div class="text-2xl font-bold text-white mb-1">₹{{ number_format($totalRevenue, 2) }}</div>
                <div class="text-xs text-indigo-100">Lifetime earnings</div>
            </div>
        </div>

        <!-- Total Campaigns -->
        <div class="card border-0 shadow-sm rounded-xl bg-white transform hover:-translate-y-1 transition-all duration-300">
            <div class="card-body p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="text-xs font-bold uppercase text-gray-400 tracking-wider">Total Campaigns</div>
                    <div class="p-2 bg-blue-50 rounded-lg text-blue-600">
                        <i class="fas fa-layer-group"></i>
                    </div>
                </div>
                <div class="text-2xl font-bold text-gray-800 mb-1">{{ $banners->total() }}</div>
                <div class="text-xs text-gray-500">All time created</div>
            </div>
        </div>

        <!-- Active Now -->
        <div class="card border-0 shadow-sm rounded-xl bg-white transform hover:-translate-y-1 transition-all duration-300">
            <div class="card-body p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="text-xs font-bold uppercase text-gray-400 tracking-wider">Active Now</div>
                    <div class="p-2 bg-green-50 rounded-lg text-green-600">
                        <i class="fas fa-broadcast-tower"></i>
                    </div>
                </div>
                <div class="text-2xl font-bold text-gray-800 mb-1">{{ $banners->where('status', 'active')->count() }}</div>
                <div class="text-xs text-green-600 font-bold">Currently Live</div>
            </div>
        </div>

        <!-- Avg CTR -->
        <div class="card border-0 shadow-sm rounded-xl bg-white transform hover:-translate-y-1 transition-all duration-300">
            <div class="card-body p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="text-xs font-bold uppercase text-gray-400 tracking-wider">Avg. CTR</div>
                    <div class="p-2 bg-cyan-50 rounded-lg text-cyan-600">
                        <i class="fas fa-mouse-pointer"></i>
                    </div>
                </div>
                <div class="text-2xl font-bold text-gray-800 mb-1">2.4%</div>
                <div class="text-xs text-gray-500">Global average</div>
            </div>
        </div>

        <!-- Pending -->
        <div class="card border-0 shadow-sm rounded-xl bg-white transform hover:-translate-y-1 transition-all duration-300">
            <div class="card-body p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="text-xs font-bold uppercase text-gray-400 tracking-wider">Pending</div>
                    <div class="p-2 bg-yellow-50 rounded-lg text-yellow-600">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
                <div class="text-2xl font-bold text-gray-800 mb-1">{{ $banners->where('status', 'pending_approval')->count() }}</div>
                <div class="text-xs text-yellow-600 font-bold">Needs Review</div>
            </div>
        </div>
    </div>

    <!-- Active Campaigns List Header -->
    <div class="flex justify-between items-center mb-4 px-2">
        <h5 class="font-bold text-gray-800 text-lg">Active Campaigns</h5>
        <div class="text-xs text-gray-500 font-medium">
            <i class="fas fa-sort mr-1"></i> Drag to reorder priority
        </div>
    </div>
    
    <!-- Modern Card List -->
    <div id="sortable-banners" class="space-y-4">
        @forelse($banners as $banner)
            <div class="card border-0 shadow-sm rounded-xl bg-white overflow-hidden hover:shadow-md transition-shadow duration-300 sortable-item group" data-id="{{ $banner->id }}">
                <div class="card-body p-0">
                    <div class="flex flex-col md:flex-row items-center">
                        
                        <!-- Drag Handle & Image -->
                        <div class="flex items-center w-full md:w-auto p-4 md:pr-0">
                            <div class="cursor-move text-gray-300 hover:text-gray-500 mr-4 transition-colors">
                                <i class="fas fa-grip-vertical text-lg"></i>
                            </div>
                            <div class="relative w-48 h-24 rounded-lg overflow-hidden shadow-sm flex-shrink-0 group-hover:shadow-md transition-all">
                                <img src="{{ $banner->image_url }}" class="w-full h-full object-cover transform group-hover:scale-105 transition-transform duration-500" alt="banner">
                                <div class="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                            </div>
                        </div>

                        <!-- Info & Creator -->
                        <div class="flex-1 p-4 w-full">
                            <div class="flex justify-between items-start">
                                <div>
                                    <h4 class="font-bold text-gray-900 text-lg mb-1">{{ $banner->title }}</h4>
                                    <!-- Created By Badge -->
                                    <div class="flex items-center mt-2">
                                        @if($banner->is_admin_created)
                                            <span class="bg-indigo-100 text-indigo-700 text-xs font-bold px-2 py-0.5 rounded-full flex items-center border border-indigo-200">
                                                <i class="fas fa-shield-alt mr-1"></i> Admin
                                            </span>
                                        @else
                                            <div class="flex items-center bg-gray-100 rounded-full pr-3 pl-1 py-0.5 border border-gray-200">
                                                <div class="w-5 h-5 rounded-full bg-gradient-to-br from-gray-400 to-gray-600 text-white flex items-center justify-center text-xs font-bold mr-2">
                                                    {{ substr($banner->user->name ?? 'U', 0, 1) }}
                                                </div>
                                                <span class="text-xs font-bold text-gray-700">{{ $banner->user->name ?? 'Unknown' }}</span>
                                            </div>
                                        @endif
                                        
                                        <span class="mx-2 text-gray-300">|</span>
                                        
                                        <span class="text-xs text-gray-500 font-medium">
                                            <i class="fas fa-map-marker-alt mr-1 text-gray-400"></i>
                                            {{ ucfirst($banner->target_location_type) }}
                                        </span>
                                    </div>
                                </div>
                                
                                <span class="bg-gray-100 text-gray-600 text-xs font-bold px-3 py-1 rounded-lg uppercase tracking-wide">
                                    {{ ucfirst($banner->redirect_type) }}
                                </span>
                            </div>
                        </div>

                        <!-- Stats -->
                        <div class="flex items-center justify-around w-full md:w-auto px-6 py-4 md:py-0 border-t md:border-t-0 md:border-l md:border-r border-gray-100 bg-gray-50/50 h-full min-h-[100px] min-w-[250px]">
                            <div class="text-center px-4">
                                <div class="text-xl font-bold text-gray-800">{{ number_format_short($banner->total_impressions) }}</div>
                                <div class="text-xs font-bold text-gray-400 uppercase tracking-wide">Views</div>
                            </div>
                            <div class="text-center px-4 border-l border-gray-200">
                                <div class="text-xl font-bold text-blue-600">{{ number_format($banner->ctr, 1) }}%</div>
                                <div class="text-xs font-bold text-blue-300 uppercase tracking-wide">CTR</div>
                            </div>
                            <div class="text-center px-4 border-l border-gray-200">
                                <div class="text-xl font-bold text-gray-800">{{ number_format_short($banner->total_clicks) }}</div>
                                <div class="text-xs font-bold text-gray-400 uppercase tracking-wide">Clicks</div>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="flex items-center p-4 w-full md:w-auto gap-4 justify-end">
                            <div class="flex flex-col items-end mr-4">
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" class="sr-only peer status-toggle" data-id="{{ $banner->id }}" {{ $banner->status === 'active' ? 'checked' : '' }}>
                                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                </label>
                                <span class="text-xs font-bold mt-1 status-text {{ $banner->status === 'active' ? 'text-blue-600' : 'text-gray-400' }}">
                                    {{ $banner->status === 'active' ? 'LIVE' : 'PAUSED' }}
                                </span>
                            </div>
                            
                            <div class="flex items-center gap-2">
                                <a href="{{ route('admin.banners.analytics', ['banner_id' => $banner->id]) }}" class="w-9 h-9 rounded-full bg-violet-50 text-violet-600 flex items-center justify-center hover:bg-violet-600 hover:text-white transition-all shadow-sm tooltip" title="Analytics">
                                    <i class="fas fa-chart-bar"></i>
                                </a>
                                <a href="{{ route('admin.banners.edit', $banner) }}" class="w-9 h-9 rounded-full bg-blue-50 text-blue-600 flex items-center justify-center hover:bg-blue-600 hover:text-white transition-all shadow-sm tooltip" title="Edit">
                                    <i class="fas fa-pencil-alt"></i>
                                </a>
                                <form action="{{ route('admin.banners.destroy', $banner) }}" method="POST" onsubmit="return confirm('Delete this campaign?')">
                                    @csrf
                                    @method('DELETE')
                                    <button class="w-9 h-9 rounded-full bg-red-50 text-red-500 flex items-center justify-center hover:bg-red-500 hover:text-white transition-all shadow-sm tooltip" title="Delete">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        @empty
            <div class="text-center py-12 bg-white rounded-xl shadow-sm border border-dashed border-gray-300">
                <div class="w-20 h-20 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-rocket text-blue-500 text-3xl"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-900 mb-2">No Campaigns Found</h3>
                <p class="text-gray-500 mb-6">Get started by creating your first banner campaign.</p>
                <a href="{{ route('admin.banners.create') }}" class="inline-flex items-center px-6 py-3 rounded-full bg-blue-600 text-white font-bold hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200">
                    <i class="fas fa-plus mr-2"></i> Create Campaign
                </a>
            </div>
        @endforelse
    </div>
</div>
</div>

<style>
/* Stats Strip Styles */
.vertical-divider {
    position: absolute;
    right: 0;
    top: 20%;
    height: 60%;
    width: 1px;
    background-color: #f0f2f5;
}

.icon-circle-sm {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
}

.icon-circle-md {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.hover-bg-light:hover { background-color: #fcfcfd; }
.transition-all { transition: all 0.3s; }

/* Custom Switch Compact */
.custom-switch-premium .custom-control-label::before {
    height: 1.25rem;
    width: 2.25rem;
    border-radius: 2rem;
}
.custom-switch-premium .custom-control-label::after {
    height: calc(1.25rem - 4px);
    width: calc(1.25rem - 4px);
    border-radius: 50%;
}

.btn-icon { width: 32px; height: 32px; padding: 0; display: inline-flex; align-items: center; justify-content: center; }

/* Colors & Shadows */
.bg-primary-subtle { background: #ebf3ff; color: #4e73df; }
.bg-success-subtle { background: #e6fffa; color: #1cc88a; }
.bg-info-subtle { background: #e0f2fe; color: #36b9cc; }
.bg-warning-subtle { background: #fffbeb; color: #f6c23e; }
.rounded-xl { border-radius: 1rem; }
.text-xxs { font-size: 0.7rem; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 1. Status Toggle
    const toggles = document.querySelectorAll('.status-toggle');
    toggles.forEach(toggle => {
        toggle.addEventListener('change', function() {
            const bannerId = this.dataset.id;
            const statusText = this.closest('td').querySelector('.status-text');
            
            // Optimistic Update
            if(this.checked) {
                statusText.textContent = 'LIVE';
                statusText.className = 'text-xs font-weight-bold mt-1 status-text text-success';
            } else {
                statusText.textContent = 'OFF';
                statusText.className = 'text-xs font-weight-bold mt-1 status-text text-muted';
            }
            
            fetch(`/admin/banners/${bannerId}/toggle-status`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Content-Type': 'application/json'
                }
            });
        });
    });

    // 2. Drag & Drop
    const el = document.getElementById('sortable-banners');
    if(el) {
        new Sortable(el, {
            handle: '.cursor-move',
            animation: 150,
            ghostClass: 'bg-light',
            onEnd: function (evt) {
                const items = [];
                document.querySelectorAll('.sortable-item').forEach(row => {
                    items.push(row.dataset.id);
                });
                fetch('{{ route("admin.banners.reorder") }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ items: items })
                });
            }
        });
    }
});
</script>

@php
    function number_format_short($n) {
        if ($n < 1000) return $n;
        $suffix = ['','k','M','G','T','P','E','Z','Y'];
        $power = floor(log($n, 1000));
        return round($n/(1000**$power),1).$suffix[$power];
    }
@endphp
@endsection
