@extends('layouts.app')
@section('title', 'Nuevo Ticket')
@section('content')
<div class="max-w-3xl">
    <div class="flex items-center gap-3 mb-6">
        <a href="{{ route('tickets.index') }}" class="text-gray-400 hover:text-gray-600">
            <svg class="h-5 w-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>
        </a>
        <h1 class="text-2xl font-bold text-gray-900">Nuevo Ticket</h1>
    </div>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <form method="POST" action="{{ route('tickets.store') }}">
            @csrf
            <div class="space-y-5">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        Título <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="title" value="{{ old('title') }}"
                           placeholder="Describe brevemente el problema o solicitud"
                           class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500 @error('title') border-red-500 @enderror">
                    @error('title') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
    {{-- Sugerencias de la Base de Conocimiento --}}
    <div id="kb-suggestions" class="hidden mt-2">
        <p class="text-xs text-blue-600 font-medium mb-2">💡 Artículos relacionados en la Base de Conocimiento:</p>
        <div id="kb-list" class="space-y-1.5"></div>
    </div>

                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        Descripción detallada <span class="text-red-500">*</span>
                    </label>
                    <textarea name="description" rows="5"
                              placeholder="Proporciona todos los detalles relevantes: qué pasó, cuándo, cómo reproducirlo..."
                              class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500 @error('description') border-red-500 @enderror">{{ old('description') }}</textarea>
                    @error('description') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Prioridad <span class="text-red-500">*</span>
                        </label>
                        <select name="priority_id"
                                class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            @foreach($priorities as $priority)
                            <option value="{{ $priority->id }}" {{ old('priority_id') == $priority->id ? 'selected' : '' }}>
                                {{ $priority->name }}
                                (SLA: {{ $priority->sla_resolution_hours }}h)
                            </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                        <select name="type_id"
                                class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Selecciona un tipo —</option>
                            @foreach($types as $type)
                            <option value="{{ $type->id }}" {{ old('type_id') == $type->id ? 'selected' : '' }}>
                                {{ $type->name }}
                            </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Categoría</label>
                        <select name="category_id"
                                class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Selecciona una categoría —</option>
                            @foreach($categories as $cat)
                            <option value="{{ $cat->id }}" {{ old('category_id') == $cat->id ? 'selected' : '' }}>
                                {{ $cat->name }}
                            </option>
                            @foreach($cat->children as $child)
                            <option value="{{ $child->id }}" {{ old('category_id') == $child->id ? 'selected' : '' }}>
                                &nbsp;&nbsp;&nbsp;└ {{ $child->name }}
                            </option>
                            @endforeach
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Departamento</label>
                        <select name="department_id"
                                class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Sin departamento —</option>
                            @foreach($departments as $dept)
                            <option value="{{ $dept->id }}" {{ old('department_id') == $dept->id ? 'selected' : '' }}>
                                {{ $dept->name }}
                            </option>
                            @endforeach
                        </select>
                    </div>

                    @if(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']))
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Asignar a agente</label>
                        <select name="assignee_id"
                                class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Sin asignar —</option>
                            @foreach($agents as $agent)
                            <option value="{{ $agent->id }}" {{ old('assignee_id') == $agent->id ? 'selected' : '' }}>
                                {{ $agent->name }}
                            </option>
                            @endforeach
                        </select>
                    </div>
                    @endif
                </div>
            </div>

            <div class="flex gap-3 mt-6 pt-5 border-t border-gray-100">
                <button type="submit"
                        class="px-5 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                    Crear Ticket
                </button>
                <a href="{{ route('tickets.index') }}"
                   class="px-5 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition">
                    Cancelar
                </a>
            </div>
        </form>
    </div>
</div>

<script>
let kbTimer;
document.querySelector('[name="title"]').addEventListener('input', function() {
    clearTimeout(kbTimer);
    const q = this.value.trim();
    if (q.length < 4) { document.getElementById('kb-suggestions').classList.add('hidden'); return; }
    kbTimer = setTimeout(() => {
        fetch('/kb/suggest?q=' + encodeURIComponent(q))
            .then(r => r.json())
            .then(data => {
                const box = document.getElementById('kb-suggestions');
                const list = document.getElementById('kb-list');
                if (!data.length) { box.classList.add('hidden'); return; }
                box.classList.remove('hidden');
                list.innerHTML = data.map(a =>
                    '<a href="' + a.url + '" target="_blank" class="flex items-center gap-2 p-2 bg-blue-50 rounded-lg hover:bg-blue-100 transition">' +
                    '<span class="text-xs text-blue-700 font-medium">📖 ' + a.title + '</span>' +
                    '</a>'
                ).join('');
            });
    }, 400);
});
</script>@endsection
