@extends('layouts.guest')

@section('content')
<div x-data="reporteForm()" x-cloak class="max-w-2xl mx-auto pb-8">

    {{-- Errores generales --}}
    @if ($errors->any())
        <div class="mb-6 bg-red-50 border border-red-300 rounded-xl p-4">
            <div class="flex items-center space-x-2 mb-2">
                <svg class="w-5 h-5 text-red-500 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <span class="text-red-700 font-semibold text-sm">Por favor corrige los siguientes errores:</span>
            </div>
            <ul class="list-disc list-inside text-sm text-red-600 space-y-1">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    {{-- Indicador de pasos --}}
    <div class="mb-8">
        <div class="flex items-center justify-center space-x-2 sm:space-x-3">
            <template x-for="s in computedTotalSteps" :key="s">
                <div class="flex items-center">
                    <button type="button"
                            @click="goToStep(s)"
                            :class="{
                                'text-white shadow-lg ring-2': step === s,
                                'text-white': s < step,
                                'bg-gray-200 text-gray-500': s > step
                            }"
                            :style="step === s ? 'background-color: #ED6B37; ring-color: rgba(237,107,55,0.3);' : (s < step ? 'background-color: #3B7FA8;' : '')"
                            class="w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold transition-all duration-200"
                            :class="step === s ? 'ring-orange-200' : ''">
                        <template x-if="s < step">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/>
                            </svg>
                        </template>
                        <template x-if="s >= step">
                            <span x-text="getDisplayStep(s)"></span>
                        </template>
                    </button>
                    <div x-show="s < computedTotalSteps"
                         :style="s < step ? 'background-color: #3B7FA8;' : ''"
                         :class="s >= step ? 'bg-gray-200' : ''"
                         class="w-6 sm:w-10 h-1 rounded-full transition-colors duration-200"></div>
                </div>
            </template>
        </div>
        <p class="text-center text-sm text-gray-500 mt-3">
            Paso <span x-text="getDisplayStep(step)"></span> de <span x-text="computedTotalSteps"></span>
        </p>
    </div>

    {{-- Formulario --}}
    <form action="{{ route('reporte.store') }}"
          method="POST"
          enctype="multipart/form-data"
          @submit="handleSubmit($event)"
          id="reporteForm">
        @csrf

        {{-- ============================================ --}}
        {{-- PASO 1: Identificacion --}}
        {{-- ============================================ --}}
        <div x-show="step === 1" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Tipo de Reporte</h2>
                <p class="text-sm text-gray-500 mb-5">Selecciona el tipo de incidente que deseas reportar.</p>

                {{-- Tipo de reporte (tarjetas) --}}
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-6">
                    @foreach ($tipos as $tipo)
                        <label class="cursor-pointer">
                            <input type="radio" name="tipo_id" value="{{ $tipo->id }}"
                                   x-model="tipoId"
                                   @change="tipoNombre = '{{ $tipo->nombre }}'"
                                   class="hidden peer"
                                   {{ old('tipo_id') == $tipo->id ? 'checked' : '' }}>
                            <div class="border-2 border-gray-200 rounded-xl p-4 text-center transition-all duration-150
                                        peer-checked:border-blue-500 peer-checked:bg-blue-50 peer-checked:shadow-md
                                        hover:border-gray-300 active:scale-[0.98]">
                                <span class="text-base font-semibold text-gray-700 peer-checked:text-blue-700">{{ $tipo->nombre }}</span>
                            </div>
                        </label>
                    @endforeach
                </div>
                @error('tipo_id')
                    <p class="text-red-500 text-sm mt-1 mb-3">{{ $message }}</p>
                @enderror

                <hr class="my-5 border-gray-100">

                {{-- Identidad --}}
                <h3 class="text-lg font-bold text-gray-800 mb-4">Identificacion del Reportante</h3>

                <div class="flex items-center bg-gray-100 rounded-xl p-1 mb-5">
                    <button type="button"
                            @click="esAnonimo = false"
                            :class="!esAnonimo ? 'bg-white shadow-sm font-semibold' : 'text-gray-500'"
                            :style="!esAnonimo ? 'color: #3B7FA8;' : ''"
                            class="flex-1 py-3 px-4 rounded-lg text-sm text-center transition-all duration-150">
                        Con Nombre
                    </button>
                    <button type="button"
                            @click="esAnonimo = true"
                            :class="esAnonimo ? 'bg-white shadow-sm font-semibold' : 'text-gray-500'"
                            :style="esAnonimo ? 'color: #3B7FA8;' : ''"
                            class="flex-1 py-3 px-4 rounded-lg text-sm text-center transition-all duration-150">
                        Anonimo
                    </button>
                </div>
                <input type="hidden" name="es_anonimo" :value="esAnonimo ? 1 : 0">

                {{-- Campos de identificacion (no anonimo) --}}
                <div x-show="!esAnonimo" x-transition class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Seleccionar trabajador</label>
                        <select name="reportado_por_user_id"
                                x-model="reportadoPorUserId"
                                class="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-base bg-white
                                       focus:ring-2 transition"
                                style="--tw-ring-color: #3B7FA8;"
                                onfocus="this.style.borderColor='#3B7FA8'; this.style.boxShadow='0 0 0 2px rgba(59,127,168,0.3)';"
                                onblur="this.style.borderColor=''; this.style.boxShadow='';">
                            <option value="">-- Seleccionar de la lista --</option>
                            @foreach ($trabajadores as $trabajador)
                                <option value="{{ $trabajador->id }}" {{ old('reportado_por_user_id') == $trabajador->id ? 'selected' : '' }}>
                                    {{ $trabajador->nombre_completo }}
                                </option>
                            @endforeach
                        </select>
                        @error('reportado_por_user_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="flex items-center space-x-3">
                        <div class="flex-1 h-px bg-gray-200"></div>
                        <span class="text-xs text-gray-400 uppercase font-medium">o escribe el nombre</span>
                        <div class="flex-1 h-px bg-gray-200"></div>
                    </div>

                    <div>
                        <input type="text" name="reportado_por_texto"
                               x-model="reportadoPorTexto"
                               placeholder="Nombre completo"
                               value="{{ old('reportado_por_texto') }}"
                               class="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-base transition"
                               onfocus="this.style.borderColor='#3B7FA8'; this.style.boxShadow='0 0 0 2px rgba(59,127,168,0.3)';"
                               onblur="this.style.borderColor=''; this.style.boxShadow='';"
                               :disabled="reportadoPorUserId !== '' && reportadoPorUserId !== null">
                        @error('reportado_por_texto')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                {{-- Aviso anonimo --}}
                <div x-show="esAnonimo" x-transition>
                    <div class="bg-amber-50 border border-amber-200 rounded-xl p-4 flex items-start space-x-3">
                        <svg class="w-6 h-6 text-amber-500 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        <div>
                            <p class="text-sm font-semibold text-amber-800">Reporte Anonimo</p>
                            <p class="text-sm text-amber-700 mt-1">
                                Al reportar de forma anonima, sera obligatorio adjuntar al menos una foto como evidencia.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- PASO 2: Ubicacion y Tiempo --}}
        {{-- ============================================ --}}
        <div x-show="step === 2" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Ubicacion y Tiempo</h2>
                <p class="text-sm text-gray-500 mb-5">Indica donde y cuando ocurrio el incidente.</p>

                <div class="space-y-5">
                    {{-- Lugar --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Lugar</label>
                        <select name="lugar_id" x-model="lugarId"
                                class="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-base bg-white transition"
                                onfocus="this.style.borderColor='#3B7FA8'; this.style.boxShadow='0 0 0 2px rgba(59,127,168,0.3)';"
                                onblur="this.style.borderColor=''; this.style.boxShadow='';">
                            <option value="">-- Seleccionar lugar --</option>
                            @foreach ($lugares as $lugar)
                                <option value="{{ $lugar->id }}" {{ old('lugar_id') == $lugar->id ? 'selected' : '' }}>
                                    {{ $lugar->nombre }}
                                </option>
                            @endforeach
                        </select>
                        @error('lugar_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    {{-- Area --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Area</label>
                        <select name="area_id" x-model="areaId"
                                class="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-base bg-white transition"
                                onfocus="this.style.borderColor='#3B7FA8'; this.style.boxShadow='0 0 0 2px rgba(59,127,168,0.3)';"
                                onblur="this.style.borderColor=''; this.style.boxShadow='';">
                            <option value="">-- Seleccionar area --</option>
                            @foreach ($areas as $area)
                                <option value="{{ $area->id }}" {{ old('area_id') == $area->id ? 'selected' : '' }}>
                                    {{ $area->nombre }}
                                </option>
                            @endforeach
                        </select>
                        @error('area_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    {{-- Turno --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Turno</label>
                        <div class="flex flex-wrap gap-3">
                            @foreach ($turnos as $turno)
                                <label class="cursor-pointer flex-1 min-w-[80px]">
                                    <input type="radio" name="turno_id" value="{{ $turno->id }}"
                                           x-model="turnoId"
                                           class="hidden peer"
                                           {{ old('turno_id') == $turno->id ? 'checked' : '' }}>
                                    <div class="border-2 border-gray-200 rounded-xl py-3 px-4 text-center text-sm font-medium
                                                transition-all duration-150
                                                peer-checked:border-blue-500 peer-checked:bg-blue-50 peer-checked:text-blue-700
                                                hover:border-gray-300 active:scale-[0.98]">
                                        {{ $turno->nombre }}
                                    </div>
                                </label>
                            @endforeach
                        </div>
                        @error('turno_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    {{-- Fecha --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Fecha y Hora</label>
                        <input type="datetime-local" name="fecha" value="{{ $fechaActual }}" readonly
                               class="w-full border border-gray-200 rounded-xl px-4 py-3.5 text-base bg-gray-50
                                      text-gray-600 cursor-not-allowed">
                        <p class="text-xs text-gray-400 mt-1">La fecha se registra automaticamente.</p>
                    </div>
                </div>
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- PASO 3: Descripcion y Riesgo --}}
        {{-- ============================================ --}}
        <div x-show="step === 3" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Descripcion del Incidente</h2>
                <p class="text-sm text-gray-500 mb-5">Describe lo ocurrido y el nivel de riesgo.</p>

                <div class="space-y-5">
                    {{-- Descripcion --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Descripcion</label>
                        <textarea name="descripcion"
                                  x-model="descripcion"
                                  maxlength="500"
                                  rows="5"
                                  placeholder="Describe detalladamente el incidente observado..."
                                  class="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-base resize-none transition"
                                  onfocus="this.style.borderColor='#3B7FA8'; this.style.boxShadow='0 0 0 2px rgba(59,127,168,0.3)';"
                                  onblur="this.style.borderColor=''; this.style.boxShadow='';">{{ old('descripcion') }}</textarea>
                        <div class="flex justify-between items-center mt-1">
                            @error('descripcion')
                                <p class="text-red-500 text-sm">{{ $message }}</p>
                            @else
                                <span></span>
                            @enderror
                            <span class="text-xs" :class="descripcion.length >= 480 ? 'text-red-500 font-semibold' : 'text-gray-400'">
                                <span x-text="descripcion.length"></span>/500
                            </span>
                        </div>
                    </div>

                    {{-- Nivel de riesgo --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-3">Nivel de Riesgo</label>
                        <div class="grid grid-cols-1 gap-3">
                            @foreach ($nivelesRiesgo as $riesgo)
                                @php
                                    $colorMap = [
                                        'Alto' => 'border-red-300 peer-checked:border-red-500 peer-checked:bg-red-50 text-red-700',
                                        'Medio' => 'border-yellow-300 peer-checked:border-yellow-500 peer-checked:bg-yellow-50 text-yellow-700',
                                        'Bajo' => 'border-green-300 peer-checked:border-green-500 peer-checked:bg-green-50 text-green-700',
                                    ];
                                    $dotMap = [
                                        'Alto' => 'bg-red-500',
                                        'Medio' => 'bg-yellow-500',
                                        'Bajo' => 'bg-green-500',
                                    ];
                                    $clase = $colorMap[$riesgo->nombre] ?? 'border-gray-300 peer-checked:border-blue-500 peer-checked:bg-blue-50 text-gray-700';
                                    $dot = $dotMap[$riesgo->nombre] ?? 'bg-gray-500';
                                @endphp
                                <label class="cursor-pointer">
                                    <input type="radio" name="riesgo_id" value="{{ $riesgo->id }}"
                                           x-model="riesgoId"
                                           @change="riesgoNombre = '{{ $riesgo->nombre }}'"
                                           class="hidden peer"
                                           {{ old('riesgo_id') == $riesgo->id ? 'checked' : '' }}>
                                    <div class="border-2 rounded-xl py-4 px-5 flex items-center space-x-3
                                                transition-all duration-150 active:scale-[0.98] {{ $clase }}">
                                        <span class="w-4 h-4 rounded-full {{ $dot }} shrink-0"></span>
                                        <span class="text-base font-semibold">{{ $riesgo->nombre }}</span>
                                    </div>
                                </label>
                            @endforeach
                        </div>
                        @error('riesgo_id')
                            <p class="text-red-500 text-sm mt-2">{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- PASO 4: Consecuencia Ambiental (condicional) --}}
        {{-- ============================================ --}}
        <div x-show="step === 4 && esAmbiental" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Consecuencia Ambiental</h2>
                <p class="text-sm text-gray-500 mb-5">Selecciona el nivel de consecuencia ambiental del incidente.</p>

                <div class="grid grid-cols-1 gap-3">
                    @foreach ($nivelesConsecuencia as $consecuencia)
                        <label class="cursor-pointer">
                            <input type="radio" name="consecuencia_id" value="{{ $consecuencia->id }}"
                                   x-model="consecuenciaId"
                                   @change="consecuenciaNombre = '{{ $consecuencia->nombre }}'"
                                   class="hidden peer"
                                   {{ old('consecuencia_id') == $consecuencia->id ? 'checked' : '' }}>
                            <div class="border-2 border-gray-200 rounded-xl py-4 px-5 text-center
                                        transition-all duration-150
                                        peer-checked:border-blue-500 peer-checked:bg-blue-50
                                        hover:border-gray-300 active:scale-[0.98]">
                                <span class="text-base font-semibold text-gray-700">{{ $consecuencia->nombre }}</span>
                            </div>
                        </label>
                    @endforeach
                </div>
                @error('consecuencia_id')
                    <p class="text-red-500 text-sm mt-2">{{ $message }}</p>
                @enderror
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- PASO 5 (o 4 si no ambiental): Evidencia --}}
        {{-- ============================================ --}}
        <div x-show="step === stepEvidencia" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Evidencia</h2>
                <p class="text-sm text-gray-500 mb-5">Adjunta fotos y tu firma.</p>

                {{-- Fotos --}}
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-3">
                        Fotos
                        <span class="text-gray-400 font-normal">(maximo 3)</span>
                        <template x-if="esAnonimo">
                            <span class="text-red-500 font-normal">*obligatorio</span>
                        </template>
                    </label>

                    {{-- Previsualizaciones --}}
                    <div class="grid grid-cols-3 gap-3 mb-3" x-show="fotoPreviews.length > 0">
                        <template x-for="(preview, index) in fotoPreviews" :key="index">
                            <div class="relative aspect-square rounded-xl overflow-hidden border-2 border-gray-200 bg-gray-50">
                                <img :src="preview" class="w-full h-full object-cover" alt="Vista previa">
                                <button type="button"
                                        @click="removePhoto(index)"
                                        class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-7 h-7
                                               flex items-center justify-center shadow-lg active:scale-90 transition">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                    </svg>
                                </button>
                            </div>
                        </template>
                    </div>

                    {{-- Boton para agregar foto --}}
                    <div x-show="fotoPreviews.length < 3">
                        <label class="cursor-pointer block">
                            <input type="file" name="fotos[]" id="fotosInput" accept="image/*" capture="environment"
                                   @change="addPhoto($event)" class="hidden" multiple>
                            <div class="border-2 border-dashed border-gray-300 rounded-xl p-6 text-center
                                        transition-colors active:scale-[0.98]"
                                 onmouseover="this.style.borderColor='#3B7FA8'; this.style.backgroundColor='rgba(59,127,168,0.05)';"
                                 onmouseout="this.style.borderColor=''; this.style.backgroundColor='';">
                                <svg class="w-10 h-10 text-gray-400 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                          d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                          d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                                </svg>
                                <p class="text-sm font-medium text-gray-600">Tomar foto o seleccionar imagen</p>
                                <p class="text-xs text-gray-400 mt-1">JPG, PNG o WebP - Max 5MB cada una</p>
                            </div>
                        </label>
                    </div>
                    @error('fotos')
                        <p class="text-red-500 text-sm mt-2">{{ $message }}</p>
                    @enderror
                    @error('fotos.*')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <hr class="my-6 border-gray-100">

                {{-- Firma --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Firma del Trabajador <span class="text-red-500">*</span>
                    </label>
                    <p class="text-xs text-gray-500 mb-3">Dibuja tu firma en el recuadro gris de abajo con el dedo o mouse.</p>
                    <div class="border-2 border-gray-300 rounded-xl overflow-hidden relative" style="background-color: #f0f0f0;"
                         :style="firmaVacia ? '' : 'border-color: #3B7FA8;'">
                        <canvas id="signatureCanvas"
                                x-ref="signatureCanvas"
                                class="w-full"
                                style="touch-action: none; height: 200px;"
                                x-init="$nextTick(() => initSignature())"></canvas>
                        <div x-show="firmaVacia"
                             class="absolute inset-0 flex items-center justify-center pointer-events-none">
                            <p class="text-gray-400 text-sm">Firme aqui</p>
                        </div>
                    </div>
                    <div class="flex justify-end mt-2">
                        <button type="button" @click="clearSignature()"
                                class="text-sm text-red-500 hover:text-red-700 font-medium py-2 px-3
                                       rounded-lg hover:bg-red-50 transition active:scale-95">
                            Borrar firma
                        </button>
                    </div>
                    <input type="hidden" name="firma_trabajador" x-model="firmaData">
                    @error('firma_trabajador')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- PASO 6 (o 5 si no ambiental): Revision --}}
        {{-- ============================================ --}}
        <div x-show="step === stepRevision" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-x-4" x-transition:enter-end="opacity-100 translate-x-0">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 sm:p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-1">Revision del Reporte</h2>
                <p class="text-sm text-gray-500 mb-5">Revisa que la informacion sea correcta antes de enviar.</p>

                <div class="space-y-4">
                    {{-- Tipo --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Tipo de reporte</p>
                            <p class="text-base font-semibold text-gray-800" x-text="tipoNombre || 'No seleccionado'"></p>
                        </div>
                        <button type="button" @click="step = 1" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Reportante --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Reportado por</p>
                            <p class="text-base font-semibold text-gray-800" x-text="getReportanteName()"></p>
                        </div>
                        <button type="button" @click="step = 1" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Lugar y Area --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Lugar / Area</p>
                            <p class="text-base font-semibold text-gray-800">
                                <span x-text="getLugarName()"></span> / <span x-text="getAreaName()"></span>
                            </p>
                        </div>
                        <button type="button" @click="step = 2" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Turno --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Turno</p>
                            <p class="text-base font-semibold text-gray-800" x-text="getTurnoName()"></p>
                        </div>
                        <button type="button" @click="step = 2" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Descripcion --}}
                    <div class="flex items-start justify-between bg-gray-50 rounded-xl p-4">
                        <div class="flex-1 mr-3">
                            <p class="text-xs text-gray-400 uppercase font-medium">Descripcion</p>
                            <p class="text-sm text-gray-700 mt-1 whitespace-pre-wrap" x-text="descripcion || 'Sin descripcion'"></p>
                        </div>
                        <button type="button" @click="step = 3" class="text-sm font-medium hover:underline shrink-0" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Riesgo --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Nivel de riesgo</p>
                            <p class="text-base font-semibold" :class="{
                                'text-red-600': riesgoNombre === 'Alto',
                                'text-yellow-600': riesgoNombre === 'Medio',
                                'text-green-600': riesgoNombre === 'Bajo',
                                'text-gray-800': !['Alto','Medio','Bajo'].includes(riesgoNombre)
                            }" x-text="riesgoNombre || 'No seleccionado'"></p>
                        </div>
                        <button type="button" @click="step = 3" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Consecuencia ambiental --}}
                    <div x-show="esAmbiental" class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Consecuencia ambiental</p>
                            <p class="text-base font-semibold text-gray-800" x-text="consecuenciaNombre || 'No seleccionado'"></p>
                        </div>
                        <button type="button" @click="step = 4" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Fotos --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Fotos adjuntas</p>
                            <p class="text-base font-semibold text-gray-800">
                                <span x-text="fotoPreviews.length"></span> foto(s)
                            </p>
                        </div>
                        <button type="button" @click="step = stepEvidencia" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>

                    {{-- Firma --}}
                    <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4">
                        <div>
                            <p class="text-xs text-gray-400 uppercase font-medium">Firma</p>
                            <p class="text-base font-semibold" :class="firmaVacia ? 'text-red-500' : 'text-green-600'"
                               x-text="firmaVacia ? 'Pendiente' : 'Completada'"></p>
                        </div>
                        <button type="button" @click="step = stepEvidencia" class="text-sm font-medium hover:underline" style="color: #3B7FA8;">Editar</button>
                    </div>
                </div>

                {{-- Boton Enviar --}}
                <div class="mt-6">
                    <button type="submit"
                            :disabled="submitting"
                            class="w-full text-white py-4 px-6 rounded-xl text-lg font-bold
                                   transition-all duration-150
                                   disabled:opacity-50 disabled:cursor-not-allowed
                                   shadow-lg active:scale-[0.98]"
                            style="background-color: #ED6B37;"
                            onmouseover="if(!this.disabled) this.style.backgroundColor='#D4592B';"
                            onmouseout="if(!this.disabled) this.style.backgroundColor='#ED6B37';"
                            onmousedown="if(!this.disabled) this.style.backgroundColor='#C04E23';"
                            onmouseup="if(!this.disabled) this.style.backgroundColor='#D4592B';">
                        <span x-show="!submitting" class="flex items-center justify-center space-x-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                            </svg>
                            <span>Enviar Reporte</span>
                        </span>
                        <span x-show="submitting" class="flex items-center justify-center space-x-2">
                            <svg class="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                            </svg>
                            <span>Enviando...</span>
                        </span>
                    </button>
                </div>
            </div>
        </div>

        {{-- ============================================ --}}
        {{-- Navegacion entre pasos --}}
        {{-- ============================================ --}}
        <div class="flex items-center justify-between mt-6" x-show="step !== stepRevision">
            <button type="button" @click="prevStep()"
                    x-show="step > 1"
                    class="flex items-center space-x-2 bg-white border border-gray-300 text-gray-700 py-3 px-5
                           rounded-xl text-base font-medium hover:bg-gray-50 active:bg-gray-100
                           transition-all duration-150 active:scale-[0.98] shadow-sm">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
                <span>Anterior</span>
            </button>
            <div x-show="step === 1"></div>

            <button type="button" @click="nextStep()"
                    class="flex items-center space-x-2 text-white py-3 px-6
                           rounded-xl text-base font-medium
                           transition-all duration-150 active:scale-[0.98] shadow-sm ml-auto"
                    style="background-color: #ED6B37;"
                    onmouseover="this.style.backgroundColor='#D4592B';"
                    onmouseout="this.style.backgroundColor='#ED6B37';"
                    onmousedown="this.style.backgroundColor='#C04E23';"
                    onmouseup="this.style.backgroundColor='#D4592B';">
                <span>Siguiente</span>
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                </svg>
            </button>
        </div>

        {{-- Boton Anterior en paso de revision --}}
        <div class="mt-6" x-show="step === stepRevision">
            <button type="button" @click="prevStep()"
                    class="flex items-center space-x-2 bg-white border border-gray-300 text-gray-700 py-3 px-5
                           rounded-xl text-base font-medium hover:bg-gray-50 active:bg-gray-100
                           transition-all duration-150 active:scale-[0.98] shadow-sm">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
                <span>Anterior</span>
            </button>
        </div>
    </form>
</div>

{{-- Signature Pad CDN --}}
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>

<script>
    // Datos de las colecciones (para lookup en revision)
    const trabajadoresMap = @json($trabajadores->pluck('nombre_completo', 'id'));
    const lugaresMap = @json($lugares->pluck('nombre', 'id'));
    const areasMap = @json($areas->pluck('nombre', 'id'));
    const turnosMap = @json($turnos->pluck('nombre', 'id'));

    function reporteForm() {
        return {
            step: 1,
            esAnonimo: {{ old('es_anonimo', 'false') === '1' ? 'true' : 'false' }},
            tipoId: '{{ old('tipo_id', '') }}',
            tipoNombre: '',
            reportadoPorUserId: '{{ old('reportado_por_user_id', '') }}',
            reportadoPorTexto: '{{ old('reportado_por_texto', '') }}',
            lugarId: '{{ old('lugar_id', '') }}',
            areaId: '{{ old('area_id', '') }}',
            turnoId: '{{ old('turno_id', '') }}',
            descripcion: '{{ old('descripcion', '') }}',
            riesgoId: '{{ old('riesgo_id', '') }}',
            riesgoNombre: '',
            consecuenciaId: '{{ old('consecuencia_id', '') }}',
            consecuenciaNombre: '',
            fotos: [],
            fotoPreviews: [],
            signaturePad: null,
            firmaData: '',
            firmaVacia: true,
            submitting: false,

            get esAmbiental() {
                return this.tipoNombre.toLowerCase().includes('ambiental');
            },

            get computedTotalSteps() {
                return this.esAmbiental ? 6 : 5;
            },

            get stepEvidencia() {
                return this.esAmbiental ? 5 : 4;
            },

            get stepRevision() {
                return this.esAmbiental ? 6 : 5;
            },

            getDisplayStep(s) {
                return s;
            },

            goToStep(targetStep) {
                if (targetStep < this.step) {
                    this.step = targetStep;
                }
            },

            nextStep() {
                if (!this.validateCurrentStep()) return;

                let next = this.step + 1;

                // Saltar paso 4 si no es ambiental
                if (next === 4 && !this.esAmbiental) {
                    next = 4; // va directo a evidencia (que es paso 4 cuando no es ambiental)
                }

                // No pasar del ultimo paso
                if (next > this.computedTotalSteps) return;

                this.step = next;
                window.scrollTo({ top: 0, behavior: 'smooth' });
            },

            prevStep() {
                let prev = this.step - 1;

                // Saltar paso 4 si no es ambiental
                if (prev === 4 && !this.esAmbiental) {
                    prev = 3;
                }

                if (prev < 1) return;
                this.step = prev;
                window.scrollTo({ top: 0, behavior: 'smooth' });
            },

            validateCurrentStep() {
                let valid = true;
                let msg = '';

                switch (this.step) {
                    case 1:
                        if (!this.tipoId) {
                            msg = 'Selecciona el tipo de reporte.';
                            valid = false;
                        } else if (!this.esAnonimo && !this.reportadoPorUserId && !this.reportadoPorTexto.trim()) {
                            msg = 'Indica quien reporta o selecciona "Anonimo".';
                            valid = false;
                        }
                        break;
                    case 2:
                        if (!this.lugarId) { msg = 'Selecciona el lugar.'; valid = false; }
                        else if (!this.areaId) { msg = 'Selecciona el area.'; valid = false; }
                        else if (!this.turnoId) { msg = 'Selecciona el turno.'; valid = false; }
                        break;
                    case 3:
                        if (!this.descripcion.trim()) { msg = 'Ingresa la descripcion del incidente.'; valid = false; }
                        else if (!this.riesgoId) { msg = 'Selecciona el nivel de riesgo.'; valid = false; }
                        break;
                    case 4:
                        if (this.esAmbiental && !this.consecuenciaId) {
                            msg = 'Selecciona el nivel de consecuencia ambiental.';
                            valid = false;
                        }
                        break;
                }

                // Validar evidencia en el paso de evidencia
                if (this.step === this.stepEvidencia) {
                    if (this.firmaVacia) {
                        msg = 'La firma es obligatoria.';
                        valid = false;
                    }
                    if (this.esAnonimo && this.fotoPreviews.length === 0) {
                        msg = 'Los reportes anonimos requieren al menos una foto.';
                        valid = false;
                    }
                }

                if (!valid) {
                    this.showAlert(msg);
                }

                return valid;
            },

            showAlert(msg) {
                // Crear notificacion temporal
                const el = document.createElement('div');
                el.className = 'fixed top-4 left-4 right-4 z-50 bg-red-500 text-white px-4 py-3 rounded-xl shadow-lg text-sm font-medium text-center transition-all duration-300';
                el.textContent = msg;
                document.body.appendChild(el);
                setTimeout(() => {
                    el.style.opacity = '0';
                    el.style.transform = 'translateY(-10px)';
                    setTimeout(() => el.remove(), 300);
                }, 3000);
            },

            addPhoto(event) {
                const files = event.target.files;
                if (!files.length) return;

                for (let i = 0; i < files.length; i++) {
                    if (this.fotoPreviews.length >= 3) break;

                    const file = files[i];
                    if (file.size > 5 * 1024 * 1024) {
                        this.showAlert('La imagen no debe superar 5MB.');
                        continue;
                    }

                    this.fotos.push(file);

                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.fotoPreviews.push(e.target.result);
                    };
                    reader.readAsDataURL(file);
                }

                // Resetear input para poder seleccionar la misma foto
                event.target.value = '';
            },

            removePhoto(index) {
                this.fotos.splice(index, 1);
                this.fotoPreviews.splice(index, 1);
            },

            initSignature() {
                const canvas = this.$refs.signatureCanvas;
                if (!canvas) return;

                // Responsive canvas size
                const resizeCanvas = () => {
                    const ratio = Math.max(window.devicePixelRatio || 1, 1);
                    const rect = canvas.getBoundingClientRect();
                    canvas.width = rect.width * ratio;
                    canvas.height = rect.height * ratio;
                    canvas.getContext('2d').scale(ratio, ratio);
                    if (this.signaturePad) {
                        this.signaturePad.clear();
                    }
                };

                resizeCanvas();

                this.signaturePad = new SignaturePad(canvas, {
                    backgroundColor: 'rgb(240, 240, 240)',
                    penColor: 'rgb(0, 51, 153)',
                    minWidth: 1,
                    maxWidth: 3,
                });

                this.signaturePad.addEventListener('endStroke', () => {
                    this.firmaVacia = this.signaturePad.isEmpty();
                    if (!this.firmaVacia) {
                        this.firmaData = this.signaturePad.toDataURL('image/png');
                    }
                });

                // Manejar resize de ventana
                window.addEventListener('resize', () => {
                    const data = this.signaturePad.toData();
                    resizeCanvas();
                    if (data.length > 0) {
                        this.signaturePad.fromData(data);
                    }
                });
            },

            clearSignature() {
                if (this.signaturePad) {
                    this.signaturePad.clear();
                    this.firmaVacia = true;
                    this.firmaData = '';
                }
            },

            getReportanteName() {
                if (this.esAnonimo) return 'Anonimo';
                if (this.reportadoPorUserId && trabajadoresMap[this.reportadoPorUserId]) {
                    return trabajadoresMap[this.reportadoPorUserId];
                }
                return this.reportadoPorTexto || 'No indicado';
            },

            getLugarName() {
                return this.lugarId ? (lugaresMap[this.lugarId] || 'No seleccionado') : 'No seleccionado';
            },

            getAreaName() {
                return this.areaId ? (areasMap[this.areaId] || 'No seleccionado') : 'No seleccionado';
            },

            getTurnoName() {
                return this.turnoId ? (turnosMap[this.turnoId] || 'No seleccionado') : 'No seleccionado';
            },

            handleSubmit(event) {
                if (this.submitting) return;

                // Validar firma
                if (this.firmaVacia) {
                    event.preventDefault();
                    this.showAlert('La firma es obligatoria.');
                    this.step = this.stepEvidencia;
                    return;
                }

                this.submitting = true;

                // Inyectar fotos almacenadas en el input file real
                const fileInput = document.getElementById('fotosInput');
                if (fileInput && this.fotos.length > 0) {
                    const dt = new DataTransfer();
                    this.fotos.forEach(f => dt.items.add(f));
                    fileInput.files = dt.files;
                }

                // El formulario se envia de forma nativa (POST estandar)
            },

            init() {
                // Inicializar tipo nombre desde old values
                @foreach ($tipos as $tipo)
                    if (this.tipoId == '{{ $tipo->id }}') this.tipoNombre = '{{ $tipo->nombre }}';
                @endforeach

                @foreach ($nivelesRiesgo as $riesgo)
                    if (this.riesgoId == '{{ $riesgo->id }}') this.riesgoNombre = '{{ $riesgo->nombre }}';
                @endforeach

                @foreach ($nivelesConsecuencia as $consecuencia)
                    if (this.consecuenciaId == '{{ $consecuencia->id }}') this.consecuenciaNombre = '{{ $consecuencia->nombre }}';
                @endforeach
            }
        };
    }
</script>

<style>
    [x-cloak] { display: none !important; }
</style>
@endsection
