@php
    $statusOptions = [
        ''           => ['label' => t('agent.status.all'),        'color' => 'gray'],
        'success'    => ['label' => t('agent.status.success'),    'color' => 'green'],
        'failed'     => ['label' => t('agent.status.failed'),     'color' => 'red'],
        'conflict'   => ['label' => t('agent.status.conflict'),   'color' => 'amber'],
        'duplicate'  => ['label' => t('agent.status.duplicate'),  'color' => 'blue'],
        'processing' => ['label' => t('agent.status.processing'), 'color' => 'purple'],
    ];

    $statusClasses = [
        'success'    => ['badge' => 'bg-green-50 text-green-700',   'dot' => 'bg-green-500'],
        'failed'     => ['badge' => 'bg-red-50 text-red-700',       'dot' => 'bg-red-500'],
        'conflict'   => ['badge' => 'bg-amber-50 text-amber-700',   'dot' => 'bg-amber-400'],
        'duplicate'  => ['badge' => 'bg-blue-50 text-blue-700',     'dot' => 'bg-blue-400'],
        'processing' => ['badge' => 'bg-purple-50 text-purple-700', 'dot' => 'bg-purple-400'],
    ];

    $typeBadges = [
        'event'        => ['#', t('agent.type.event'),          '#4F46E5', '#EEF2FF'],
        'event_update' => ['✎', t('agent.type.event_update'),   '#4F46E5', '#EEF2FF'],
        'note'         => ['#', t('agent.type.note'),           '#B45309', '#FFFBEB'],
        'note_update'  => ['✎', t('agent.type.note_update'),    '#B45309', '#FFFBEB'],
        'task'         => ['#', t('agent.type.task'),           '#065F46', '#ECFDF5'],
        'task_update'  => ['✎', t('agent.type.task_update'),    '#065F46', '#ECFDF5'],
        'contact'      => ['#', t('agent.type.contact'),        '#1E40AF', '#EFF6FF'],
        'email'        => ['#', t('agent.type.email'),          '#6B21A8', '#FAF5FF'],
        'chat'         => ['#', t('agent.type.chat'),           '#374151', '#F3F4F6'],
        'multi'        => ['#', t('agent.type.multi'),          '#9D174D', '#FDF2F8'],
        'bonus'        => ['#', t('agent.type.bonus'),          '#065F46', '#ECFDF5'],
        'system'       => ['#', t('agent.type.system'),         '#374151', '#F9FAFB'],
    ];
@endphp

<div class="space-y-6">

    {{-- HEADER --}}
    <div class="flex items-start justify-between">
        <div>
            <h2 class="text-xl font-semibold text-gray-800">{{ t('agent.logs.title') }}</h2>
            <p class="text-sm text-gray-500 mt-1">
                @if(auth()->user()->isDeveloper())
                    {{ t('agent.logs.subtitle_admin') }}
                @else
                    {{ t('agent.logs.subtitle') }}
                @endif
            </p>
        </div>
        <a href="{{ route('agent.index') }}"
           class="flex items-center gap-1.5 text-xs text-gray-400 hover:text-indigo-600 border border-gray-200 hover:border-indigo-200 px-3 py-1.5 rounded-lg transition-colors">
            <x-heroicon-o-arrow-left class="w-3.5 h-3.5"/>
            {{ t('agent.logs.go_assistant') }}
        </a>
    </div>


    {{-- STATS --}}
    @if($stats && $stats->total > 0)
        @php
            $successRate = $stats->total > 0
                ? round(($stats->successes / $stats->total) * 100)
                : 0;
            $avgDurationSec = $stats->avg_duration
                ? ($stats->avg_duration >= 1000
                    ? round($stats->avg_duration / 1000, 1) . 's'
                    : round($stats->avg_duration) . 'ms')
                : '—';
        @endphp
        {{-- Credit-Card mit Fortschritt --}}
        @if(auth()->user()->isUnlimitedUser())
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 rounded-lg bg-amber-50 flex items-center justify-center shrink-0">
                            <x-heroicon-o-bolt class="w-4 h-4 text-amber-500"/>
                        </div>
                        <span class="text-sm text-gray-500">{{ t('agent.logs.credits_month') }}</span>
                    </div>
                    <span style="display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:500;background:#F0FDF4;color:#065F46;border:1px solid #10B98122;">
                        <span style="width:6px;height:6px;border-radius:50%;background:#10B981;display:inline-block;flex-shrink:0;"></span>
                        {{ t('agent.unlimited') }}
                    </span>
                </div>
            </div>
        @else
            @php
                $roleDefault = match(auth()->user()->role) {
                    \App\Enums\UserRole::Admin      => ['bg' => '#FAF5FF', 'color' => '#7E22CE', 'dot' => '#9333EA', 'bar' => 'bg-purple-600'],
                    \App\Enums\UserRole::Developer  => ['bg' => '#F0FDF4', 'color' => '#15803D', 'dot' => '#22C55E', 'bar' => 'bg-green-600'],
                    \App\Enums\UserRole::Support    => ['bg' => '#EFF6FF', 'color' => '#1D4ED8', 'dot' => '#3B82F6', 'bar' => 'bg-blue-500'],
                    \App\Enums\UserRole::Affiliate  => ['bg' => '#FDF4FF', 'color' => '#A21CAF', 'dot' => '#D946EF', 'bar' => 'bg-fuchsia-500'],
                    \App\Enums\UserRole::BetaTester => ['bg' => '#FFF7ED', 'color' => '#C2410C', 'dot' => '#F97316', 'bar' => 'bg-orange-500'],
                    default                         => ['bg' => '#EEF2FF', 'color' => '#3730A3', 'dot' => '#4F46E5', 'bar' => 'bg-indigo-600'],
                };

                $creditBadge = match(true) {
                    $usagePercent >= 100 => ['label' => t('agent.full'),             'bg' => '#FEF2F2', 'color' => '#991B1B', 'dot' => '#EF4444', 'bar' => 'bg-red-500'],
                    $usagePercent >= 80  => ['label' => $usage . ' / ' . $limit,    'bg' => '#FFFBEB', 'color' => '#92400E', 'dot' => '#F59E0B', 'bar' => 'bg-amber-500'],
                    $usagePercent >= 60  => ['label' => $usage . ' / ' . $limit,    'bg' => '#FFF7ED', 'color' => '#9A3412', 'dot' => '#FB923C', 'bar' => 'bg-orange-400'],
                    default              => array_merge($roleDefault, ['label' => $usage . ' / ' . $limit]),
                };
            @endphp
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 rounded-lg bg-amber-50 flex items-center justify-center shrink-0">
                            <x-heroicon-o-bolt class="w-4 h-4 text-amber-500"/>
                        </div>
                        <span class="text-sm text-gray-500">{{ t('agent.logs.credits_month') }}</span>
                    </div>
                    <span style="display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:500;background:{{ $creditBadge['bg'] }};color:{{ $creditBadge['color'] }};border:1px solid {{ $creditBadge['color'] }}22;">
                        <span style="width:6px;height:6px;border-radius:50%;background:{{ $creditBadge['dot'] }};display:inline-block;flex-shrink:0;"></span>
                        {{ $creditBadge['label'] }}
                    </span>
                </div>
                <div class="w-full bg-gray-100 rounded-full h-1.5 mb-1">
                    <div class="{{ $creditBadge['bar'] }} h-1.5 rounded-full transition-all duration-500"
                         style="width: {{ min(100, $usagePercent) }}%"></div>
                </div>
                <div class="text-xs text-gray-400">
                    {{ $usagePercent }}% {{ t('agent.logs.used') }}
                </div>
            </div>
        @endif

        {{-- Übrige Stat-Cards --}}
        @php
            $statCards = [
                ['label' => t('agent.logs.requests_month'),  'value' => number_format($stats->total),  'sub' => null,                                            'icon' => 'cpu-chip',     'color' => 'text-indigo-600', 'bg' => 'bg-indigo-50'],
                ['label' => t('agent.logs.success_rate'),       'value' => $successRate . '%',             'sub' => $stats->failures . ' ' . t('agent.logs.errors'),  'icon' => 'check-circle', 'color' => 'text-green-600',  'bg' => 'bg-green-50'],
            ];
            if (auth()->user()->isDeveloper()) {
                $statCards[] = ['label' => t('agent.logs.avg_response'), 'value' => $avgDurationSec, 'sub' => number_format($stats->total_tokens ?? 0) . ' Tokens', 'icon' => 'clock', 'color' => 'text-blue-600', 'bg' => 'bg-blue-50'];
            }
        @endphp
        <div class="grid grid-cols-2 {{ auth()->user()->isDeveloper() ? 'md:grid-cols-3' : 'md:grid-cols-2' }} gap-3">
            @foreach($statCards as $stat)
                <div class="bg-white border border-gray-100 rounded-xl px-4 py-3.5 flex items-center gap-3 shadow-sm">
                    <div class="w-8 h-8 rounded-lg {{ $stat['bg'] }} flex items-center justify-center shrink-0">
                        @if($stat['icon'] === 'cpu-chip')         <x-heroicon-o-cpu-chip class="w-4 h-4 {{ $stat['color'] }}"/>
                        @elseif($stat['icon'] === 'check-circle') <x-heroicon-o-check-circle class="w-4 h-4 {{ $stat['color'] }}"/>
                        @else                                     <x-heroicon-o-clock class="w-4 h-4 {{ $stat['color'] }}"/>
                        @endif
                    </div>
                    <div>
                        <p class="text-lg font-semibold text-gray-800 leading-none">{{ $stat['value'] }}</p>
                        <p class="text-xs text-gray-400 mt-0.5">{{ $stat['sub'] ?? $stat['label'] }}</p>
                    </div>
                </div>
            @endforeach
        </div>
    @endif


    {{-- FILTER + SUCHE --}}
    <div class="bg-white border border-gray-100 rounded-xl shadow-sm p-4 flex flex-col sm:flex-row gap-3 items-start sm:items-center">

        {{-- Suche --}}
        <div class="relative flex-1 w-full">
            <x-heroicon-o-magnifying-glass class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"/>
            <input wire:model.live.debounce.300ms="search"
                   type="text"
                   placeholder="{{ t('agent.logs.search') }}"
                   class="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-indigo-400 placeholder:text-gray-400">
        </div>

        {{-- Status-Filter --}}
        <div class="flex flex-wrap gap-1.5 shrink-0">
            @foreach($statusOptions as $key => $opt)
                @php
                    $active = $filterStatus === $key;
                    $colorMap = [
                        'green'  => $active ? 'bg-green-600 text-white border-green-600'  : 'bg-white text-gray-500 border-gray-200 hover:border-green-300 hover:text-green-700',
                        'red'    => $active ? 'bg-red-600 text-white border-red-600'      : 'bg-white text-gray-500 border-gray-200 hover:border-red-300 hover:text-red-700',
                        'amber'  => $active ? 'bg-amber-500 text-white border-amber-500'  : 'bg-white text-gray-500 border-gray-200 hover:border-amber-300 hover:text-amber-700',
                        'blue'   => $active ? 'bg-blue-600 text-white border-blue-600'    : 'bg-white text-gray-500 border-gray-200 hover:border-blue-300 hover:text-blue-700',
                        'purple' => $active ? 'bg-purple-600 text-white border-purple-600': 'bg-white text-gray-500 border-gray-200 hover:border-purple-300 hover:text-purple-700',
                        'gray'   => $active ? 'bg-indigo-600 text-white border-indigo-600': 'bg-white text-gray-500 border-gray-200 hover:border-gray-300 hover:text-gray-700',
                    ];
                @endphp
                <button wire:click="$set('filterStatus', '{{ $key }}')"
                        class="px-2.5 py-1.5 rounded-lg text-xs font-medium border transition-all {{ $colorMap[$opt['color']] }}">
                    {{ $opt['label'] }}
                </button>
            @endforeach
        </div>

    </div>


    {{-- LOGS LISTE --}}
    @if($logs->isEmpty())

        <div class="bg-white border border-gray-100 rounded-xl shadow-sm py-16 flex flex-col items-center gap-3">
            <div class="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center">
                <x-heroicon-o-cpu-chip class="w-6 h-6 text-gray-400"/>
            </div>
            <p class="text-sm font-medium text-gray-600">{{ t('agent.logs.no_entries') }}</p>
            @if($search || $filterStatus)
                <button wire:click="$set('search', ''); $set('filterStatus', '')"
                        class="text-xs text-indigo-600 hover:underline mt-1">{{ t('common.reset_filter') }}</button>
            @else
                <p class="text-xs text-gray-400">{{ t('agent.logs.no_entries_hint') }}</p>
            @endif
        </div>

    @else

        <div class="bg-white border border-gray-100 rounded-xl shadow-sm divide-y divide-gray-50">
            @foreach($logs as $log)
                @php
                    $sc = $statusClasses[$log->status] ?? ['badge' => 'bg-gray-100 text-gray-500', 'dot' => 'bg-gray-400'];
                    $badge = $typeBadges[$log->type] ?? ['#', ucfirst($log->type ?? '?'), '#374151', '#F9FAFB'];

                    // Dauer formatieren
                    if ($log->duration_ms !== null) {
                        $dur = $log->duration_ms >= 1000
                            ? round($log->duration_ms / 1000, 1) . 's'
                            : $log->duration_ms . 'ms';
                    } else {
                        $dur = '—';
                    }

                    // Kosten formatieren
                    $cost = $log->cost_usd > 0
                        ? '$' . number_format($log->cost_usd, 4)
                        : '—';
                @endphp

                <div class="px-5 py-4 hover:bg-gray-50/50 transition-colors" wire:key="log-{{ $log->id }}">

                    <div class="flex items-start gap-4">

                        {{-- Status-Dot --}}
                        <div class="mt-1.5 shrink-0">
                            <span class="block w-2 h-2 rounded-full {{ $sc['dot'] }}"></span>
                        </div>

                        {{-- Inhalt --}}
                        <div class="flex-1 min-w-0">

                            {{-- Eingabe + Zeit --}}
                            <div class="flex items-start justify-between gap-3">
                                <p class="text-sm text-gray-800 leading-snug truncate">{{ $log->output['title'] ?? $log->input }}</p>
                                <span class="text-[11px] text-gray-300 whitespace-nowrap shrink-0">
                                    {{ $log->created_at->setTimezone($tz)->format('d.m. H:i') }}
                                </span>
                            </div>

                            {{-- Badges + Metriken --}}
                            <div class="flex flex-wrap items-center gap-2 mt-2">

                                {{-- Typ --}}
                                <span style="display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:500;background:{{ $badge[3] }};color:{{ $badge[2] }};border:1px solid {{ $badge[2] }}22;">
                                    <span style="width:5px;height:5px;border-radius:50%;background:{{ $badge[2] }};display:inline-block;flex-shrink:0;"></span>
                                    {{ $badge[1] }}{{ $badge[0] === '✎' ? ' ✎' : '' }}
                                </span>

                                {{-- Status --}}
                                <span class="text-[10px] font-medium {{ $sc['badge'] }} px-1.5 py-0.5 rounded-md">
                                    {{ $statusOptions[$log->status]['label'] ?? $log->status }}
                                </span>

                                {{-- Trennstrich --}}
                                <span class="text-gray-200">|</span>

                                {{-- Credits (alle User) --}}
                                <span class="flex items-center gap-1 text-[11px] text-gray-400">
                                    <x-heroicon-o-bolt class="w-3 h-3 text-amber-400"/>
                                    {{ $log->credits }} Credits
                                </span>

                                {{-- Zeitstempel relativ (alle User) --}}
                                <span class="flex items-center gap-1 text-[11px] text-gray-400">
                                    <x-heroicon-o-clock class="w-3 h-3 text-gray-300"/>
                                    {{ $log->created_at->diffForHumans() }}
                                </span>

                                {{-- Admin-only: Tokens, Dauer, Kosten, Modell --}}
                                @if(auth()->user()->isDeveloper())

                                    <span class="text-gray-200">|</span>

                                    {{-- Tokens --}}
                                    @if($log->total_tokens > 0)
                                        <span class="flex items-center gap-1 text-[11px] text-gray-400">
                                            <x-heroicon-o-document-text class="w-3 h-3 text-gray-300"/>
                                            {{ number_format($log->total_tokens) }} Tokens
                                            <span class="text-gray-300">({{ number_format($log->prompt_tokens) }}↑ {{ number_format($log->completion_tokens) }}↓)</span>
                                        </span>
                                    @endif

                                    {{-- Dauer --}}
                                    <span class="flex items-center gap-1 text-[11px] text-gray-400">
                                        <x-heroicon-o-clock class="w-3 h-3 text-gray-300"/>
                                        {{ $dur }}
                                    </span>

                                    {{-- Kosten --}}
                                    @if($log->cost_usd > 0)
                                        <span class="text-[11px] text-gray-400">{{ $cost }}</span>
                                    @endif

                                    {{-- Modell --}}
                                    @if($log->model)
                                        <span class="text-[10px] text-gray-300 bg-gray-50 border border-gray-100 px-1.5 py-0.5 rounded-md font-mono">
                                            {{ $log->model }}
                                        </span>
                                    @endif

                                @endif

                            </div>

                            {{-- Fehler-Ausgabe bei failed --}}
                            @if($log->status === 'failed' && !empty($log->output['error']))
                                <p class="text-[11px] text-red-400 mt-1.5 truncate">
                                    <x-heroicon-o-exclamation-triangle class="w-3 h-3 inline-block mr-0.5"/>
                                    {{ $log->output['error'] }}
                                </p>
                            @endif

                        </div>

                    </div>

                </div>
            @endforeach
        </div>

        {{-- PAGINATION --}}
        @if($logs->hasPages())
            <div class="flex items-center justify-between text-sm text-gray-500 pt-2">
                <span class="text-xs">
                    {{ $logs->firstItem() }}–{{ $logs->lastItem() }} {{ t('common.of') }} {{ $logs->total() }} {{ t('common.entries') }}
                </span>
                <div class="flex gap-1">
                    @if($logs->onFirstPage())
                        <span class="px-3 py-1.5 rounded-lg border border-gray-100 text-gray-300 text-xs cursor-default">‹</span>
                    @else
                        <button wire:click="previousPage"
                                class="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 text-xs transition-colors">‹</button>
                    @endif

                    @foreach($logs->getUrlRange(max(1, $logs->currentPage() - 2), min($logs->lastPage(), $logs->currentPage() + 2)) as $page => $url)
                        <button wire:click="gotoPage({{ $page }})"
                                class="px-3 py-1.5 rounded-lg border text-xs transition-colors
                                    {{ $page === $logs->currentPage()
                                        ? 'bg-indigo-600 text-white border-indigo-600'
                                        : 'border-gray-200 text-gray-600 hover:bg-gray-50' }}">
                            {{ $page }}
                        </button>
                    @endforeach

                    @if($logs->hasMorePages())
                        <button wire:click="nextPage"
                                class="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 text-xs transition-colors">›</button>
                    @else
                        <span class="px-3 py-1.5 rounded-lg border border-gray-100 text-gray-300 text-xs cursor-default">›</span>
                    @endif
                </div>
            </div>
        @endif

    @endif

</div>
