@extends('layouts.app')
@section('title','Plantillas de Respuesta IA')
@section('content')

<div class="mb-6 flex items-center justify-between">
    <div>
        <h1 class="text-xl font-bold text-gray-900">⚡ Plantillas de Respuesta IA</h1>
        <p class="text-sm text-gray-500 mt-1">Se activan automáticamente según keywords del ticket</p>
    </div>
    <a href="{{ route('ai.admin') }}" class="text-sm text-blue-600 hover:underline">← IA Admin</a>
</div>

@if(session('success'))
<div class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg text-sm text-green-700">{{ session('success') }}</div>
@endif

<div class="grid grid-cols-3 gap-6">
    {{-- Lista --}}
    <div class="col-span-2 bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 border-b border-gray-100 flex items-center justify-between">
            <h2 class="text-sm font-semibold">{{ $templates->total() }} plantillas</h2>
        </div>
        @forelse($templates as $t)
        <div class="p-4 border-b border-gray-100 last:border-0">
            <div class="flex items-start justify-between gap-3">
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2 mb-1">
                        <p class="text-sm font-medium text-gray-900">{{ $t->name }}</p>
                        <span class="text-xs {{ $t->active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500' }} px-1.5 py-0.5 rounded">
                            {{ $t->active ? 'Activa' : 'Inactiva' }}
                        </span>
                        @if($t->category)<span class="text-xs bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded">{{ $t->category->name }}</span>@endif
                    </div>
                    <p class="text-xs text-gray-500 mb-1 line-clamp-2">{{ $t->template_body }}</p>
                    <div class="flex items-center gap-3 text-xs text-gray-400">
                        <span>Keywords: {{ implode(', ', array_slice($t->trigger_keywords, 0, 4)) }}{{ count($t->trigger_keywords) > 4 ? '...' : '' }}</span>
                        <span>Usada: {{ $t->uses }}x · Aceptada: {{ $t->accept_rate }}%</span>
                    </div>
                </div>
                <div class="flex items-center gap-1 flex-shrink-0">
                    <button onclick="editTemplate({{ $t->id }}, {{ json_encode($t) }})"
                            class="px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded transition">Editar</button>
                    <form method="POST" action="{{ route('ai.templates.destroy', $t) }}" onsubmit="return confirm('¿Eliminar?')">
                        @csrf @method('DELETE')
                        <button class="px-2 py-1 text-xs text-red-500 hover:bg-red-50 rounded transition">Eliminar</button>
                    </form>
                </div>
            </div>
        </div>
        @empty
        <div class="p-8 text-center text-gray-400 text-sm">Sin plantillas. Crea la primera.</div>
        @endforelse
        <div class="p-4">{{ $templates->links() }}</div>
    </div>

    {{-- Formulario --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
        <h2 class="text-sm font-semibold mb-4" id="form-title">Nueva plantilla</h2>
        <form method="POST" action="{{ route('ai.templates.store') }}" id="template-form" class="space-y-3">
            @csrf
            <input type="hidden" name="_method" id="form-method" value="">
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Nombre</label>
                <input type="text" name="name" id="f-name" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" required>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Keywords activadoras <span class="text-gray-400">(separadas por coma)</span></label>
                <input type="text" name="trigger_keywords" id="f-keywords" placeholder="contrasena, acceso, no puedo entrar" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" required>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Categoría (opcional)</label>
                <select name="category_id" id="f-category" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm">
                    <option value="">Cualquier categoría</option>
                    @foreach($categories as $cat)
                    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Confianza mínima (%)</label>
                <input type="number" name="min_confidence" id="f-confidence" value="30" min="0" max="100" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm">
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Cuerpo de la respuesta</label>
                <p class="text-xs text-gray-400 mb-1">Variables: @{{solicitante}}, @{{ticket}}, @{{titulo}}, @{{categoria}}, @{{agente}}</p>
                <textarea name="template_body" id="f-body" rows="8" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono resize-none" required></textarea>
            </div>
            <button type="submit" class="w-full py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                Guardar plantilla
            </button>
            <button type="button" onclick="resetForm()" class="w-full py-2 bg-gray-100 text-gray-600 text-sm rounded-lg hover:bg-gray-200 transition hidden" id="cancel-btn">
                Cancelar
            </button>
        </form>
    </div>
</div>

@endsection
<script>
function editTemplate(id, data) {
    document.getElementById('form-title').textContent = 'Editar plantilla';
    document.getElementById('template-form').action = '/ai/templates/' + id;
    document.getElementById('form-method').value = 'PATCH';
    document.getElementById('f-name').value = data.name;
    document.getElementById('f-keywords').value = data.trigger_keywords.join(', ');
    document.getElementById('f-category').value = data.category_id || '';
    document.getElementById('f-confidence').value = data.min_confidence;
    document.getElementById('f-body').value = data.template_body;
    document.getElementById('cancel-btn').classList.remove('hidden');
    window.scrollTo(0, document.getElementById('template-form').offsetTop - 100);
}
function resetForm() {
    document.getElementById('form-title').textContent = 'Nueva plantilla';
    document.getElementById('template-form').reset();
    document.getElementById('template-form').action = '{{ route("ai.templates.store") }}';
    document.getElementById('form-method').value = '';
    document.getElementById('cancel-btn').classList.add('hidden');
}
</script>
