<div>
    {{-- Header --}}
    <div class="fixed top-0 left-0 right-0 w-full bg-white flex items-center justify-between p-4 z-50 border-b border-gray-200">
        <div class="flex items-center">
            <img src="{{ Storage::url('images_static/tresipunt-square.svg') }}" alt="Logo" class="w-10 h-10 mr-3">
            <h1 class="text-2xl font-bold">Crear un nuevo entorno</h1>
        </div>
        <div class="flex items-center gap-3">
            <a href="{{ route('environments.index') }}"
                class="text-gray-700 hover:text-gray-900 px-4 py-2">
                Cancelar
            </a>
            {{-- **La cabecera solo cancela.** Tenía además un «Atrás» y un «Siguiente»
                 que hacían exactamente lo mismo que los botones del pie de cada paso,
                 y el «Siguiente» **seguía saliendo en el paso 2**, donde `nextStep()`
                 solo valida y no avanza: parecía la acción principal y no hacía nada.
                 Las acciones de cada paso viven en su propia tarjeta, que es donde
                 está la vista. --}}
        </div>
    </div>

    {{-- Steps (solo visible en steps 1 y 2) --}}
    @if($currentStep < 3)
        <div class="pt-20 pb-4">
            @include('livewire.components.steps-partial', ['steps' => ['Cliente', 'Entorno'], 'currentStep' => $currentStep])
        </div>
    @endif

    {{-- Contenido según step --}}
    <div class="w-full px-20 pt-8 pb-4">
        <div class="mx-auto max-w-3xl sm:px-6 lg:px-8">
            <div class="w-full flex flex-wrap items-center justify-between mt-8 rounded-lg @if($currentStep !== 3) bg-white border border-gray-200 @endif px-8 py-4">

                @if($currentStep === 1)
                    {{-- Step 1: Selección de cliente --}}
                    <div class="w-full">
                        <div class="w-full flex items-center justify-center flex-col mb-8">
                            <h1 class="text-4xl font-bold">Selecciona el cliente</h1>
                            <p class="text-gray-500 text-sm text-center mt-2">
                                Selecciona un cliente para asociar el nuevo entorno.
                            </p>
                        </div>

                        {{-- Búsqueda --}}
                        <div class="mb-6">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Buscar cliente</label>
                            <div class="relative">
                                <img src="{{ asset('vendor/blade-untitledui-icons/search-lg.svg') }}" alt="Buscar"
                                    class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400">
                                <input type="text" wire:model.live="searchQuery"
                                    class="w-full rounded-t-lg border border-gray-200 pl-10 pr-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    placeholder="Nombre o shortname del cliente">
                            </div>
                        </div>

                        {{-- Lista de clientes --}}
                        <div class="space-y-2 max-h-96 overflow-y-auto border-l border-r border-b rounded-b-lg border-gray-200 p-2">
                            @forelse($this->clients as $client)
                                <label class="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer {{ $selectedClientId === $client->id ? 'bg-blue-50 border-blue-500' : '' }}">
                                    <input type="radio" wire:model.live="selectedClientId" value="{{ $client->id }}"
                                        class="mr-4 w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
                                    <div class="flex-1">
                                        <div class="font-medium text-gray-900">{{ $client->name }}</div>
                                        <div class="text-sm text-gray-500">{{ $client->environments_count }} entorno(s)</div>
                                    </div>
                                </label>
                            @empty
                                {{-- **El vacío da la salida.** Un «no se encontraron
                                     clientes» deja el asistente en un callejón: si el
                                     cliente no existe todavía, lo que hay que hacer es
                                     crearlo, y desde aquí no había forma de llegar. --}}
                                <div class="text-center py-8">
                                    @if(trim($searchQuery) !== '')
                                        <p class="text-gray-500">
                                            Ningún cliente coincide con «{{ trim($searchQuery) }}».
                                        </p>
                                        <button type="button" wire:click="$set('searchQuery', '')"
                                            class="mt-2 text-sm font-medium text-blue-600 hover:underline">
                                            Ver todos los clientes
                                        </button>
                                    @else
                                        <p class="text-gray-500">Todavía no hay ningún cliente.</p>
                                    @endif

                                    @can('admin.clients.create')
                                        <p class="mt-4 text-sm text-gray-500">
                                            Un entorno tiene que ir asociado a un cliente.
                                            <a href="{{ route('clients.create') }}" wire:navigate
                                               class="font-medium text-blue-600 hover:underline">Dar de alta un cliente</a>
                                            y vuelve aquí.
                                        </p>
                                    @endcan
                                </div>
                            @endforelse
                        </div>

                        {{-- Paginación --}}
                        <div class="mt-4">
                            @include('livewire.components.simple-pagination', ['paginator' => $this->clients])
                        </div>

                        {{-- **Dice a qué paso lleva**, no «Siguiente»: en esta pantalla
                             convivía con el «Página siguiente» de la paginación, justo
                             encima, y con otro «Siguiente» en la cabecera. --}}
                        <div class="mt-6 flex items-center justify-end gap-4">
                            @if(!$selectedClientId)
                                <span class="text-sm text-gray-500">Elige un cliente para continuar</span>
                            @endif
                            <button wire:click="nextStep" wire:loading.attr="disabled"
                                class="bg-3ip hover:bg-3ip-light text-white px-6 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
                                @if(!$selectedClientId) disabled @endif>
                                Datos del entorno
                            </button>
                        </div>
                    </div>

                @elseif($currentStep === 2)
                    {{-- Step 2: Formulario de entorno --}}
                    <div class="w-full">
                        <div class="w-full flex items-center justify-center flex-col mb-8">
                            <h1 class="text-4xl font-bold">Datos del entorno</h1>
                            {{-- **Se nombra el cliente.** Decía «para el cliente
                                 seleccionado» sin decir cuál, así que después de buscar
                                 y paginar no había forma de confirmar que era el que se
                                 quería sin volver atrás. --}}
                            @if($cliente = $this->clienteElegido())
                                <p class="text-gray-500 text-sm text-center mt-2">
                                    Para <span class="font-semibold text-gray-800">{{ $cliente->name }}</span>
                                    @if($cliente->shortname)
                                        <span class="font-mono text-xs text-gray-500">{{ $cliente->shortname }}</span>
                                    @endif
                                    · <button type="button" wire:click="previousStep"
                                        class="font-medium text-blue-600 hover:underline">cambiar</button>
                                </p>
                            @endif
                        </div>

                        <form wire:submit="saveEnvironment" class="w-full flex flex-col gap-6">
                            {{-- Nombre --}}
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Nombre</label>
                                <input type="text" wire:model="formData.name"
                                    class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.name') border-red-500 @enderror"
                                    {{-- Decía «Introduce tu nombre»: es el nombre del entorno, no el de quien lo crea. --}}
                                    placeholder="Campus de Formación, Aula Virtual…"
                                    required>
                                @error('formData.name')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- Dominio / URL --}}
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Dominio / URL</label>
                                <input type="text" wire:model="formData.domain"
                                    class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.domain') border-red-500 @enderror"
                                    placeholder="www.tresipunt.com"
                                    required>
                                @error('formData.domain')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- Descripción --}}
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Descripción</label>
                                <textarea wire:model="formData.description" rows="3"
                                    class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.description') border-red-500 @enderror"
                                    placeholder="Escribe una breve descripción del entorno aquí..."></textarea>
                                @error('formData.description')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- Grid de 2 columnas para selects --}}
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {{-- Tipo de entorno --}}
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Tipo de entorno</label>
                                    <select wire:model="formData.type_id"
                                        class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.type_id') border-red-500 @enderror">
                                        <option value="">Selecciona el tipo</option>
                                        @foreach($types as $type)
                                            <option value="{{ $type->id }}">{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('formData.type_id')
                                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                    @enderror
                                </div>

                                {{-- Versión --}}
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Versión</label>
                                    <input type="text" wire:model="formData.version"
                                        class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.version') border-red-500 @enderror"
                                        {{-- Es un campo de texto, no un desplegable: decía «Selecciona». --}}
                                        placeholder="5.1.1"
                                        required>
                                    @error('formData.version')
                                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                    @enderror
                                </div>

                                {{-- Desarrollo --}}
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Desarrollo</label>
                                    <select wire:model="formData.env"
                                        class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('formData.env') border-red-500 @enderror"
                                        required>
                                        <option value="">Selecciona el desarrollo</option>
                                        @foreach(\App\Models\Environments\Environment::envs() as $key => $label)
                                            <option value="{{ $key }}">{{ $label }}</option>
                                        @endforeach
                                    </select>
                                    @error('formData.env')
                                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                    @enderror
                                </div>
                            </div>

                            {{-- Botones --}}
                            <div class="w-full flex items-center justify-end mt-8">
                                {{-- **Decía «Cancelar» y volvía al paso 1.** Era mentira:
                                     parecía abandonar el alta y lo que hacía era ir atrás,
                                     con el «Cancelar» de verdad —el que sale al listado—
                                     arriba y con la misma palabra. --}}
                                <button type="button" wire:click="previousStep"
                                    class="bg-white hover:bg-gray-100 border border-gray-300 text-gray-700 px-4 py-2 rounded-lg">
                                    Atrás
                                </button>
                                <button type="submit" wire:loading.attr="disabled"
                                    class="bg-3ip hover:bg-3ip-light text-white px-4 py-2 rounded-lg ml-4">
                                    <span wire:loading.remove wire:target="saveEnvironment">Crear entorno</span>
                                    <span wire:loading wire:target="saveEnvironment">Guardando...</span>
                                </button>
                            </div>
                        </form>
                    </div>

                @elseif($currentStep === 3)
                    {{-- Step 3: Página de éxito --}}
                    @if($createdEnvironmentId)
                        <livewire:environments.components.success :environment_id="$createdEnvironmentId" :embedded="true" />
                    @endif
                @endif
            </div>
        </div>
    </div>
</div>

