<div class="space-y-6"
     x-data="{
         inputText: '',
         pendingMessage: null,
         sending: false,
         ...agentVoiceOrb(),
         sendMessage() {
             if (!this.inputText.trim() || this.sending) return;
             this.sending = true;
             this.pendingMessage = this.inputText.trim();
             const msg = this.pendingMessage;
             this.inputText = '';
             $nextTick(() => {
                 this.$refs.chatScroll.scrollTop = this.$refs.chatScroll.scrollHeight;
             });
             $wire.call('send', msg).then(() => {
                 this.pendingMessage = null;
                 this.sending = false;
                 $nextTick(() => {
                     this.$refs.chatScroll.scrollTop = this.$refs.chatScroll.scrollHeight;
                     this.$refs.chatInput.focus();
                 });
             });
         }
     }"
     x-init="initVoice()"
     x-on:conversation-ended.window="setTimeout(() => {
         $wire.clearConversation();
         $wire.dispatch('notify', {
             type: 'info',
             title: '{{ t('agent.conversation_ended') }}',
             message: '{{ t('agent.ready_new') }}'
         });
     }, 4000)">

    {{-- HEADER --}}
    <div class="flex items-start justify-between">
        <div>
            <h2 class="text-xl font-semibold text-gray-800">{{ t('agent.title') }}</h2>
            <p class="text-sm text-gray-500 mt-1">{{ t('agent.subtitle') }}</p>
        </div>
        <div class="flex items-center gap-2">
            <span class="flex items-center gap-1.5 text-xs text-green-600 bg-green-50 border border-green-100 px-2.5 py-1 rounded-full">
                <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span>
                {{ t('agent.active') }}
            </span>
            @if(count($conversation) > 0)
                <button wire:click="clearConversation"
                        class="flex items-center gap-1.5 text-xs text-gray-400 hover:text-red-500 border border-gray-200 hover:border-red-200 px-3 py-1.5 rounded-lg transition-colors">
                    <x-heroicon-o-trash class="w-3.5 h-3.5"/>
                    {{ t('agent.new_conversation') }}
                </button>
            @endif
            <a href="{{ route('agent.logs') }}"
               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-clock class="w-3.5 h-3.5"/>
                {{ t('agent.history') }}
            </a>
        </div>
    </div>


    {{-- USAGE --}}
    @if(auth()->user()->isUnlimitedUser())
        <div class="bg-white border border-gray-100 rounded-xl shadow-sm px-5 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <x-heroicon-o-bolt class="w-4 h-4 text-amber-500"/>
                    <span class="text-sm font-medium text-gray-700">{{ t('agent.credits') }}</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;"></span>
                    {{ t('agent.unlimited') }}
                </span>
            </div>
        </div>
    @else
        @php
            $barColor = match(true) {
                $usagePercent >= 100 => 'bg-red-500',
                $usagePercent >= 80  => 'bg-amber-500',
                $usagePercent >= 60  => 'bg-yellow-400',
                default              => 'bg-indigo-600',
            };
            $creditBadge = match(true) {
                $usagePercent >= 100 => [
                    'label' => t('agent.full'),
                    'bg'    => '#FEF2F2',
                    'color' => '#991B1B',
                    'dot'   => '#EF4444',
                ],
                $usagePercent >= 80 => [
                    'label' => $usage . ' / ' . $limit,
                    'bg'    => '#FFFBEB',
                    'color' => '#92400E',
                    'dot'   => '#F59E0B',
                ],
                $usagePercent >= 60 => [
                    'label' => $usage . ' / ' . $limit,
                    'bg'    => '#FFF7ED',
                    'color' => '#9A3412',
                    'dot'   => '#FB923C',
                ],
                default => [
                    'label' => $usage . ' / ' . $limit,
                    'bg'    => '#EEF2FF',
                    'color' => '#3730A3',
                    'dot'   => '#4F46E5',
                ],
            };
        @endphp
        <div class="bg-white border border-gray-100 rounded-xl shadow-sm px-5 py-4">
            <div class="flex items-center justify-between mb-2">
                <div class="flex items-center gap-2">
                    <x-heroicon-o-bolt class="w-4 h-4 text-amber-500"/>
                    <span class="text-sm font-medium text-gray-700">{{ t('agent.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">
                <div class="{{ $barColor }} h-1.5 rounded-full transition-all duration-500"
                     style="width: {{ min($usagePercent, 100) }}%"></div>
            </div>
            @php
                $planLimit = auth()->user()->subscription?->plan?->credit_limit ?? 0;
                $bonusLeft = auth()->user()->bonus_credits;
            @endphp
            @if($bonusLeft > 0)
                <p class="text-[11px] text-gray-400 mt-1.5">
                    {{ number_format($planLimit) }} {{ t('agent.plan') }} +
                    <span class="text-indigo-500 font-medium">{{ number_format($bonusLeft) }} {{ t('agent.balance') }}</span>
                </p>
            @endif
            @if($limit > 0 && $usagePercent >= 80 && $usagePercent < 100)
                <p class="text-xs text-amber-600 mt-1">{{ t('agent.almost_used') }} — <a href="{{ route('plans.index') }}" class="underline">{{ t('agent.upgrade_pro') }}</a></p>
            @elseif($limit > 0 && $usagePercent >= 100)
                <p class="text-xs text-red-600 mt-1">{{ t('agent.quota_exhausted') }} — <a href="{{ route('plans.index') }}" class="underline">{{ t('agent.upgrade_now') }}</a></p>
            @endif
        </div>
    @endif


    {{-- LAYOUT: CHAT (links) + VERLAUF (rechts) --}}
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        {{-- LEFT: CHAT --}}
        <div class="lg:col-span-2 space-y-4">

            {{-- VOICE ORB OVERLAY --}}
            <div x-show="voiceMode" x-cloak x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
                 wire:ignore
                 class="bg-white border border-gray-100 rounded-xl shadow-sm flex flex-col items-center justify-center relative overflow-hidden"
                 style="min-height: 500px;">

                {{-- Close Button --}}
                <button x-on:click="stopVoice()"
                        class="absolute top-4 right-4 z-10 w-8 h-8 flex items-center justify-center rounded-lg text-gray-300 hover:text-gray-500 hover:bg-gray-100 transition-all">
                    <x-heroicon-o-x-mark class="w-5 h-5"/>
                </button>

                {{-- 3D Orb Container --}}
                <div class="flex-1 flex items-center justify-center" x-ref="orbContainer"></div>

                {{-- Bottom section --}}
                <div class="pb-8 pt-2 flex flex-col items-center gap-4 w-full max-w-sm px-6">

                    {{-- Live Transcript --}}
                    <div class="min-h-[48px] flex items-center justify-center w-full">
                        <p x-show="voiceState === 'listening' && transcript" x-cloak
                           class="text-sm text-gray-600 text-center leading-relaxed"
                           x-text="transcript"></p>
                        <p x-show="voiceState === 'idle'" class="text-xs text-gray-300">{{ t('agent.ready') }}</p>
                        <p x-show="voiceState === 'listening' && !transcript"
                           class="text-sm text-indigo-500">{{ t('agent.speak_now') }}</p>
                        <p x-show="voiceState === 'thinking'"
                           class="text-sm text-purple-500">{{ t('agent.thinking') }}</p>
                        <p x-show="voiceState === 'speaking'"
                           class="text-sm text-indigo-500">{{ t('agent.answering') }}</p>
                    </div>

                    {{-- Stop Button --}}
                    <button x-on:click="stopVoice()"
                            class="px-5 py-2 bg-gray-50 hover:bg-gray-100 text-gray-500 hover:text-gray-700 rounded-full text-xs font-medium transition-all border border-gray-200">
                        {{ t('agent.end_conversation') }}
                    </button>
                </div>
            </div>


            {{-- CHAT CARD (hidden when voice mode) --}}
            <div x-show="!voiceMode" class="bg-white border border-gray-100 rounded-xl shadow-sm flex flex-col" style="min-height: 500px;">

                {{-- CHAT MESSAGES --}}
                <div class="flex-1 overflow-y-auto p-5 space-y-4" x-ref="chatScroll"
                     x-init="$nextTick(() => $refs.chatScroll.scrollTop = $refs.chatScroll.scrollHeight)"
                     x-effect="$wire.conversation; $nextTick(() => $refs.chatScroll.scrollTop = $refs.chatScroll.scrollHeight)">

                    {{-- Willkommen wenn leer --}}
                    @if(count($conversation) === 0)
                        <div x-show="!pendingMessage" class="flex flex-col items-center justify-center h-full text-center py-12">
                            <div class="w-14 h-14 rounded-2xl bg-indigo-50 flex items-center justify-center mb-4">
                                <x-heroicon-o-sparkles class="w-7 h-7 text-indigo-600"/>
                            </div>
                            <p class="text-sm font-medium text-gray-800">{{ t('agent.greeting') }}</p>
                            <p class="text-xs text-gray-400 mt-1 max-w-sm">
                                {{ t('agent.intro') }}
                            </p>

                            {{-- Quick-Chips --}}
                            <div class="flex gap-2 flex-wrap justify-center mt-5">
                                <button x-on:click="inputText = '{{ t('agent.prompt_event') }}'; $nextTick(() => $refs.chatInput.focus())"
                                        class="px-3 py-1.5 bg-gray-50 hover:bg-indigo-50 border border-gray-200 hover:border-indigo-200 text-gray-500 hover:text-indigo-600 rounded-lg text-xs transition-colors">
                                    {{ t('agent.create_event') }}
                                </button>
                                <button x-on:click="inputText = '{{ t('agent.prompt_note') }}'; $nextTick(() => $refs.chatInput.focus())"
                                        class="px-3 py-1.5 bg-gray-50 hover:bg-indigo-50 border border-gray-200 hover:border-indigo-200 text-gray-500 hover:text-indigo-600 rounded-lg text-xs transition-colors">
                                    {{ t('agent.create_note') }}
                                </button>
                                <button x-on:click="inputText = '{{ t('agent.prompt_chat') }}'; $nextTick(() => $refs.chatInput.focus())"
                                        class="px-3 py-1.5 bg-gray-50 hover:bg-indigo-50 border border-gray-200 hover:border-indigo-200 text-gray-500 hover:text-indigo-600 rounded-lg text-xs transition-colors">
                                    {{ t('agent.just_chat') }}
                                </button>
                            </div>
                        </div>
                    @endif

                    {{-- Nachrichten --}}
                    @foreach($conversation as $msg)
                        @if($msg['role'] === 'user')
                            <div class="flex justify-end">
                                <div class="max-w-[80%] bg-indigo-600 text-white rounded-2xl rounded-br-md px-4 py-2.5">
                                    <p class="text-sm">{{ $msg['content'] }}</p>
                                </div>
                            </div>
                        @else
                            <div class="flex justify-start gap-2.5">
                                <div class="w-7 h-7 rounded-lg bg-indigo-50 flex items-center justify-center shrink-0 mt-0.5">
                                    <x-heroicon-o-sparkles class="w-4 h-4 text-indigo-600"/>
                                </div>
                                <div class="max-w-[80%] bg-gray-100 text-gray-800 rounded-2xl rounded-bl-md px-4 py-2.5">
                                    <p class="text-sm">{{ str_replace('[END]', '', $msg['content']) }}</p>
                                </div>
                            </div>
                        @endif
                    @endforeach

                    {{-- Optimistische User-Nachricht --}}
                    <template x-if="pendingMessage">
                        <div class="flex justify-end">
                            <div class="max-w-[80%] bg-indigo-600 text-white rounded-2xl rounded-br-md px-4 py-2.5">
                                <p class="text-sm" x-text="pendingMessage"></p>
                            </div>
                        </div>
                    </template>

                    {{-- Typing Indicator --}}
                    <div x-show="pendingMessage" x-cloak class="flex justify-start gap-2.5">
                        <div class="w-7 h-7 rounded-lg bg-indigo-50 flex items-center justify-center shrink-0 mt-0.5">
                            <x-heroicon-o-sparkles class="w-4 h-4 text-indigo-600"/>
                        </div>
                        <div class="bg-gray-100 rounded-2xl rounded-bl-md px-4 py-3">
                            <div class="flex items-center gap-1">
                                <span class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0ms"></span>
                                <span class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 150ms"></span>
                                <span class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 300ms"></span>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- AKTIONS-FEEDBACK --}}
                @if($lastAction)
                    @php
                        $isSuccess = in_array($lastAction['status'], ['success', 'duplicate']);
                        $isFailed  = $lastAction['status'] === 'failed';
                    @endphp
                    <div class="mx-5 mb-3 border rounded-xl p-3 flex items-start gap-3
                        {{ $isSuccess ? 'bg-green-50 border-green-100'  : '' }}
                        {{ $isFailed  ? 'bg-red-50 border-red-100'      : '' }}
                        {{ !$isSuccess && !$isFailed ? 'bg-amber-50 border-amber-100' : '' }}">

                        <div class="w-6 h-6 rounded-lg flex items-center justify-center shrink-0
                            {{ $isSuccess ? 'bg-green-100'  : '' }}
                            {{ $isFailed  ? 'bg-red-100'    : '' }}
                            {{ !$isSuccess && !$isFailed ? 'bg-amber-100' : '' }}">
                            @if($isSuccess)  <x-heroicon-o-check class="w-3.5 h-3.5 text-green-600"/>
                            @elseif($isFailed) <x-heroicon-o-x-mark class="w-3.5 h-3.5 text-red-500"/>
                            @else            <x-heroicon-o-exclamation-triangle class="w-3.5 h-3.5 text-amber-500"/>
                            @endif
                        </div>

                        <div class="flex-1 min-w-0">
                            <p class="text-xs font-medium
                                {{ $isSuccess ? 'text-green-700' : '' }}
                                {{ $isFailed  ? 'text-red-600'   : '' }}
                                {{ !$isSuccess && !$isFailed ? 'text-amber-700' : '' }}">
                                {{ $lastAction['message'] }}
                            </p>
                            @if(!empty($lastAction['meta']['title']) || !empty($lastAction['meta']['date']))
                                <p class="text-[11px] text-gray-500 mt-0.5">
                                    @if(!empty($lastAction['meta']['title'])){{ $lastAction['meta']['title'] }}@endif
                                    @if(!empty($lastAction['meta']['date'])) &middot; {{ $lastAction['meta']['date'] }}@endif
                                </p>
                            @endif
                        </div>
                    </div>
                @endif

                {{-- INPUT --}}
                <div class="border-t border-gray-100 p-4">
                    <div class="flex gap-2">
                        <input x-model="inputText"
                               x-ref="chatInput"
                               x-on:keydown.enter.prevent="sendMessage()"
                               type="text"
                               placeholder="{{ t('agent.placeholder') }}"
                               class="flex-1 border border-gray-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-400 placeholder:text-gray-400"
                               :disabled="sending">

                        {{-- Voice Button --}}
                        <button x-show="supported"
                                x-on:click="toggleVoice()"
                                class="p-2.5 rounded-xl transition-colors border border-gray-200 hover:border-indigo-300 hover:bg-indigo-50 text-gray-400 hover:text-indigo-600"
                                :class="voiceMode && 'bg-indigo-50 border-indigo-300 text-indigo-600'">
                            <x-heroicon-o-microphone class="w-5 h-5"/>
                        </button>

                        {{-- Send Button --}}
                        <button x-on:click="sendMessage()"
                                :disabled="sending"
                                class="bg-indigo-600 hover:bg-indigo-700 text-white p-2.5 rounded-xl transition-colors disabled:opacity-60">
                            <x-heroicon-o-paper-airplane class="w-5 h-5" x-show="!sending"/>
                            <svg x-show="sending" x-cloak class="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" stroke-dasharray="32" stroke-dashoffset="12"/>
                            </svg>
                        </button>
                    </div>
                </div>

            </div>

        </div>


        {{-- RIGHT: VERLAUF --}}
        <div class="bg-white border border-gray-100 rounded-xl shadow-sm p-5 h-fit space-y-4">

            <div class="flex items-center justify-between">
                <p class="text-sm font-semibold text-gray-800">{{ t('agent.last_requests') }}</p>
                <a href="{{ route('agent.logs') }}"
                   class="text-xs text-indigo-600 hover:underline">{{ t('agent.view_all') }}</a>
            </div>

            <livewire:agent.history/>

        </div>

    </div>

</div>
