@extends('layouts.brand')

@section('title', 'A/B Test Dashboard - ' . $ad->name)

@section('content')
<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-1">A/B Test Dashboard</h1>
                    <p class="text-muted mb-0">{{ $ad->name }}</p>
                </div>
                <div class="btn-group">
                    <a href="{{ route('brand.ads.export', $ad) }}" class="btn btn-success">
                        <i class="fas fa-download me-2"></i>Export Results
                    </a>
                    <a href="{{ route('brand.ads.show', $ad) }}" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i>Back to Ad
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Performance Overview -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Overall Performance</h5>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        @php
                            $totalImpressions = $variantsWithMetrics->sum('total_impressions');
                            $totalClicks = $variantsWithMetrics->sum('total_clicks');
                            $totalConversions = $variantsWithMetrics->sum('total_conversions');
                            $totalSpend = $variantsWithMetrics->sum('total_spend');
                            $overallCTR = $totalImpressions > 0 ? ($totalClicks / $totalImpressions) * 100 : 0;
                            $overallConvRate = $totalClicks > 0 ? ($totalConversions / $totalClicks) * 100 : 0;
                        @endphp
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">TOTAL IMPRESSIONS</h6>
                                <h3 class="mb-0">{{ number_format($totalImpressions) }}</h3>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">TOTAL CLICKS</h6>
                                <h3 class="mb-0">{{ number_format($totalClicks) }}</h3>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">CONVERSIONS</h6>
                                <h3 class="mb-0">{{ number_format($totalConversions) }}</h3>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">AVG CTR</h6>
                                <h3 class="mb-0">{{ number_format($overallCTR, 2) }}%</h3>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">CONV. RATE</h6>
                                <h3 class="mb-0">{{ number_format($overallConvRate, 2) }}%</h3>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="p-3">
                                <h6 class="text-muted small mb-2">TOTAL SPEND</h6>
                                <h3 class="mb-0">{{ $ad->currency }} {{ number_format($totalSpend, 2) }}</h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Best Performing Variant -->
    @if($bestVariant)
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-warning">
                    <div class="card-header bg-warning">
                        <h5 class="mb-0">
                            <i class="fas fa-trophy me-2"></i>Best Performing Variant (by CTR)
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h6 class="text-muted small mb-1">HEADLINE</h6>
                                <p class="fw-bold mb-2">{{ $bestVariant['variant']->headline }}</p>
                                <h6 class="text-muted small mb-1">BODY</h6>
                                <p class="mb-2">{{ $bestVariant['variant']->body }}</p>
                                <h6 class="text-muted small mb-1">CTA</h6>
                                <p class="mb-0"><span class="badge bg-primary">{{ $bestVariant['variant']->cta }}</span></p>
                            </div>
                            <div class="col-md-6">
                                <div class="row text-center">
                                    <div class="col-6 mb-3">
                                        <h6 class="text-muted small mb-1">CTR</h6>
                                        <h4 class="text-success mb-0">{{ number_format($bestVariant['avg_ctr'], 2) }}%</h4>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <h6 class="text-muted small mb-1">CONVERSIONS</h6>
                                        <h4 class="text-success mb-0">{{ number_format($bestVariant['total_conversions']) }}</h4>
                                    </div>
                                    <div class="col-6">
                                        <h6 class="text-muted small mb-1">IMPRESSIONS</h6>
                                        <h4 class="mb-0">{{ number_format($bestVariant['total_impressions']) }}</h4>
                                    </div>
                                    <div class="col-6">
                                        <h6 class="text-muted small mb-1">CLICKS</h6>
                                        <h4 class="mb-0">{{ number_format($bestVariant['total_clicks']) }}</h4>
                                    </div>
                                </div>
                                @if(!$bestVariant['variant']->is_winner)
                                    <form action="{{ route('brand.ads.variants.promote', $bestVariant['variant']) }}" method="POST" class="mt-3">
                                        @csrf
                                        <button type="submit" class="btn btn-warning w-100">
                                            <i class="fas fa-trophy me-2"></i>Promote as Winner
                                        </button>
                                    </form>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif

    <!-- Variant Comparison -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-balance-scale me-2"></i>Variant Comparison</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Variant</th>
                                    <th>Status</th>
                                    <th>Impressions</th>
                                    <th>Clicks</th>
                                    <th>CTR</th>
                                    <th>Conversions</th>
                                    <th>Conv. Rate</th>
                                    <th>Spend</th>
                                    <th>CPC</th>
                                    <th>ROAS</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($variantsWithMetrics->sortByDesc('avg_ctr') as $variantData)
                                    <tr class="{{ $variantData['variant']->is_winner ? 'table-warning' : '' }}">
                                        <td>
                                            <div class="d-flex align-items-center">
                                                @if($variantData['variant']->is_winner)
                                                    <i class="fas fa-trophy text-warning me-2"></i>
                                                @endif
                                                <div>
                                                    <div class="fw-bold">{{ Str::limit($variantData['variant']->headline, 30) }}</div>
                                                    <small class="text-muted">{{ Str::limit($variantData['variant']->body, 40) }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge bg-{{ $variantData['variant']->is_active ? 'success' : 'secondary' }}">
                                                {{ $variantData['variant']->is_active ? 'Active' : 'Inactive' }}
                                            </span>
                                        </td>
                                        <td>{{ number_format($variantData['total_impressions']) }}</td>
                                        <td>{{ number_format($variantData['total_clicks']) }}</td>
                                        <td>
                                            <span class="badge bg-{{ $variantData['avg_ctr'] > 1 ? 'success' : 'secondary' }}">
                                                {{ number_format($variantData['avg_ctr'], 2) }}%
                                            </span>
                                        </td>
                                        <td>{{ number_format($variantData['total_conversions']) }}</td>
                                        <td>{{ number_format($variantData['avg_conversion_rate'], 2) }}%</td>
                                        <td>{{ $ad->currency }} {{ number_format($variantData['total_spend'], 2) }}</td>
                                        <td>{{ $ad->currency }} {{ number_format($variantData['avg_cpc'], 2) }}</td>
                                        <td>{{ number_format($variantData['avg_roas'], 2) }}x</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Performance Charts -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">CTR Comparison</h5>
                </div>
                <div class="card-body">
                    <canvas id="ctrChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Conversion Rate Comparison</h5>
                </div>
                <div class="card-body">
                    <canvas id="conversionChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Metrics by Variant -->
    <div class="row">
        @foreach($variantsWithMetrics as $index => $variantData)
            <div class="col-md-6 col-lg-4 mb-4">
                <div class="card h-100 {{ $variantData['variant']->is_winner ? 'border-warning' : '' }}">
                    <div class="card-header {{ $variantData['variant']->is_winner ? 'bg-warning' : '' }}">
                        <h6 class="mb-0">
                            @if($variantData['variant']->is_winner)
                                <i class="fas fa-trophy me-2"></i>
                            @endif
                            Variant #{{ $index + 1 }}
                            <span class="badge bg-{{ $variantData['variant']->is_active ? 'success' : 'secondary' }} float-end">
                                {{ $variantData['variant']->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <h6 class="text-muted small mb-1">HEADLINE</h6>
                            <p class="fw-bold small mb-0">{{ $variantData['variant']->headline }}</p>
                        </div>
                        <div class="mb-3">
                            <h6 class="text-muted small mb-1">PERFORMANCE METRICS</h6>
                            <div class="row g-2">
                                <div class="col-6">
                                    <div class="border rounded p-2 text-center">
                                        <small class="text-muted d-block">Impressions</small>
                                        <strong>{{ number_format($variantData['total_impressions']) }}</strong>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="border rounded p-2 text-center">
                                        <small class="text-muted d-block">Clicks</small>
                                        <strong>{{ number_format($variantData['total_clicks']) }}</strong>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="border rounded p-2 text-center">
                                        <small class="text-muted d-block">CTR</small>
                                        <strong class="text-{{ $variantData['avg_ctr'] > 1 ? 'success' : 'muted' }}">
                                            {{ number_format($variantData['avg_ctr'], 2) }}%
                                        </strong>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="border rounded p-2 text-center">
                                        <small class="text-muted d-block">Conversions</small>
                                        <strong>{{ number_format($variantData['total_conversions']) }}</strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Prepare data for charts
    const variantLabels = [
        @foreach($variantsWithMetrics as $index => $variantData)
            'Variant #{{ $index + 1 }}',
        @endforeach
    ];
    
    const ctrData = [
        @foreach($variantsWithMetrics as $variantData)
            {{ $variantData['avg_ctr'] }},
        @endforeach
    ];
    
    const conversionData = [
        @foreach($variantsWithMetrics as $variantData)
            {{ $variantData['avg_conversion_rate'] }},
        @endforeach
    ];

    // CTR Chart
    const ctrCtx = document.getElementById('ctrChart').getContext('2d');
    new Chart(ctrCtx, {
        type: 'bar',
        data: {
            labels: variantLabels,
            datasets: [{
                label: 'CTR (%)',
                data: ctrData,
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            }
        }
    });

    // Conversion Rate Chart
    const convCtx = document.getElementById('conversionChart').getContext('2d');
    new Chart(convCtx, {
        type: 'bar',
        data: {
            labels: variantLabels,
            datasets: [{
                label: 'Conversion Rate (%)',
                data: conversionData,
                backgroundColor: 'rgba(75, 192, 192, 0.5)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            }
        }
    });
});
</script>
@endpush
@endsection