@extends('layouts.app')
@section('title', $ticket->number)
@section('content')
<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>
    <div class="flex items-center gap-3">
        <span class="text-lg font-mono font-bold text-blue-600">{{ $ticket->number }}</span>
        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
              style="background-color: {{ $ticket->status->color }}20; color: {{ $ticket->status->color }}">
            {{ $ticket->status->name }}
        </span>
        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
              style="background-color: {{ $ticket->priority->color }}20; color: {{ $ticket->priority->color }}">
            {{ $ticket->priority->name }}
        </span>
        @php $sla = $ticket->sla_status @endphp
        @if($sla === 'breached')
        <span class="text-sm text-red-600 font-semibold">⚠ SLA vencido</span>
        @elseif($sla === 'warning')
        <span class="text-sm text-yellow-600 font-semibold">⏰ {{ $ticket->sla_remaining }}</span>
        @elseif($sla === 'ok')
        <span class="text-sm text-green-600">✓ {{ $ticket->sla_remaining }}</span>
        @endif
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Columna principal --}}
    <div class="lg:col-span-2 space-y-5">

        {{-- Título y descripción --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-xl font-bold text-gray-900 mb-3">{{ $ticket->title }}</h2>
            <div class="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed">{{ $ticket->description }}</div>
        </div>

        {{-- Comentarios --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">
                    Actividad ({{ $ticket->comments->count() }} comentarios)
                </h3>
            </div>
            <div class="divide-y divide-gray-100">
                @forelse($ticket->comments as $comment)
                @if(!$comment->is_internal || auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']))
                <div class="px-6 py-4 {{ $comment->is_internal ? 'bg-yellow-50' : '' }}">
                    <div class="flex items-center gap-2 mb-2">
                        <img src="{{ $comment->user->avatar_url }}" class="h-7 w-7 rounded-full">
                        <span class="text-sm font-medium text-gray-900">{{ $comment->user->name }}</span>
                        <span class="text-xs text-gray-400">{{ $comment->created_at->diffForHumans() }}</span>
                        @if($comment->is_internal)
                        <span class="text-xs bg-yellow-200 text-yellow-800 px-2 py-0.5 rounded-full">Nota interna</span>
                        @endif
                    </div>
                    <p class="text-sm text-gray-700 whitespace-pre-wrap">{{ $comment->body }}</p>
                </div>
                @endif
                @empty
                <div class="px-6 py-8 text-center text-gray-400 text-sm">Sin comentarios aún.</div>
                @endforelse
            </div>

            {{-- Agregar comentario --}}
            <div class="px-6 py-4 border-t border-gray-200 bg-gray-50 rounded-b-xl">
                <form method="POST" action="{{ route('tickets.comment', $ticket) }}">
                    @csrf
                    
                    {{-- Plantillas de respuesta rápida --}}
                    @if(auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']))
                    <div class="mb-2" x-data="{ open: false }">
                        <button type="button" @click="open = !open"
                                class="text-xs text-blue-600 hover:text-blue-800 font-medium" id="reply-template-btn">
                            &#9889; Usar plantilla
                        </button>
                        <div x-show="open" x-transition @click.outside="open=false"
                             class="mt-2 bg-white border border-gray-200 rounded-xl shadow-lg p-3 max-h-64 overflow-y-auto">
                            <input type="text" id="template-search" placeholder="Buscar plantilla..."
                                   oninput="searchTemplates(this.value)"
                                   class="w-full rounded-lg border-gray-300 text-xs mb-2 focus:ring-blue-500 focus:border-blue-500">
                            <div id="template-list" class="space-y-1"></div>
                        </div>
                    </div>
                    @endif

                {{-- Botón Respuesta IA --}}
                @if(auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']))
                
                {{-- ═══ SELECTOR DE PLANTILLAS DE RESPUESTA ═══ --}}
                @php
                    $replyTemplates = \App\Models\ReplyTemplate::active()
                        ->orderBy('name')
                        ->get(['id', 'name', 'shortcut', 'body']);
                @endphp
                @if($replyTemplates->count())
                <div class="mb-3" id="reply-templates-wrapper">
                    <div class="flex items-center gap-2">
                        <label class="text-xs font-medium text-gray-500 whitespace-nowrap">
                            📋 Plantilla:
                        </label>
                        <select id="reply-template-select"
                                class="flex-1 rounded-lg border-gray-300 text-sm
                                       focus:ring-blue-500 focus:border-blue-500 py-1.5">
                            <option value="">— Seleccionar plantilla de respuesta —</option>
                            @foreach($replyTemplates as $tpl)
                            <option value="{{ $tpl->id }}"
                                    data-body="{{ e($tpl->body) }}"
                                    data-shortcut="{{ $tpl->shortcut }}">
                                {{ $tpl->name }}
                                @if($tpl->shortcut)
                                    <span class="text-gray-400">({{ $tpl->shortcut }})</span>
                                @endif
                            </option>
                            @endforeach
                        </select>
                    </div>
                    <p class="text-xs text-gray-400 mt-1">
                        Los marcadores <code>@verbatim{{solicitante}}@endverbatim</code> y <code>@verbatim{{ticket}}@endverbatim</code>
                        se reemplazan automáticamente.
                        También puedes escribir el shortcut (ej: <code>/saludo</code>) en el texto.
                    </p>
                </div>
                @endif
<div class="flex items-center gap-2 mb-2">
                    <button type="button" id="ai-response-btn"
                            onclick="loadAiResponse({{ $ticket->id }})"
                            class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition font-medium">
                        <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                        </svg>
                        Respuesta IA
                    </button>
                    <span id="ai-response-status" class="text-xs text-gray-400 hidden">Generando...</span>
                </div>
                @endif

                <textarea name="body" rows="3" placeholder="Escribe tu comentario..."
                              class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500 mb-3"></textarea>
                    <div class="flex items-center justify-between">
                        @if(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']))
                        <label class="flex items-center gap-2 text-sm text-gray-600">
                            <input type="checkbox" name="is_internal" value="1" class="rounded border-gray-300 text-yellow-500">
                            Nota interna (solo visible para agentes)
                        </label>
                        @else
                        <span></span>
                        @endif
                        <button type="submit"
                                class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                            Comentar
                        </button>
                    </div>
                </form>
            </div>
        </div>

        {{-- Historial --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">Historial de cambios</h3>
            </div>
            <div class="px-6 py-4 space-y-2">
                @foreach($ticket->history as $event)
                <div class="flex items-start gap-3 text-sm">
                    <div class="h-1.5 w-1.5 rounded-full bg-blue-400 mt-2 flex-shrink-0"></div>
                    <div>
                        <span class="text-gray-700">{{ $event->description }}</span>
                        <span class="text-gray-400 text-xs ml-2">
                            {{ $event->user?->name ?? 'Sistema' }} · {{ $event->created_at->format('d/m/y H:i') }}
                        </span>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>

    {{-- Panel lateral --}}
    <div class="space-y-5">

        {{-- Acciones de estado --}}
        @if(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']))
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-3">Cambiar Estado</h3>
            <form method="POST" action="{{ route('tickets.status', $ticket) }}">
                @csrf @method('PATCH')
                <select name="status_id" class="w-full rounded-lg border-gray-300 text-sm mb-3 focus:ring-blue-500 focus:border-blue-500">
                    @foreach($statuses as $status)
                    <option value="{{ $status->id }}" {{ $ticket->status_id == $status->id ? 'selected' : '' }}>
                        {{ $status->name }}
                    </option>
                    @endforeach
                </select>
                <textarea name="comment" rows="2" placeholder="Comentario del cambio (opcional)..."
                          class="w-full rounded-lg border-gray-300 text-sm mb-3 focus:ring-blue-500 focus:border-blue-500"></textarea>
                <button type="submit"
                        class="w-full py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                    Actualizar Estado
                </button>
            </form>
        </div>
        @endif

        
                {{-- Panel IA --}}
                @php $aiClass = $ticket->aiClassification ?? null; @endphp
                @if($aiClass && $aiClass->is_confident && auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']))
                <div class="bg-white rounded-xl shadow-sm border border-blue-200 p-4 mb-4" id="ai-classification-panel">
                    <div class="flex items-center gap-2 mb-3">
                        <span class="text-lg">🤖</span>
                        <p class="text-sm font-semibold text-gray-900">Sugerencias de IA</p>
                        <span class="ml-auto text-xs text-gray-400">clasificación automática</span>
                    </div>
                    @if($aiClass->suggestedCategory)
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs text-gray-500">Categoría sugerida:</span>
                        <div class="flex items-center gap-1">
                            <span class="text-xs font-medium text-blue-700 bg-blue-50 px-2 py-0.5 rounded">{{ $aiClass->suggestedCategory->name }}</span>
                            <span class="text-xs text-gray-400">{{ $aiClass->category_confidence }}%</span>
                        </div>
                    </div>
                    @endif
                    @if($aiClass->suggestedPriority)
                    <div class="flex items-center justify-between mb-3">
                        <span class="text-xs text-gray-500">Prioridad sugerida:</span>
                        <div class="flex items-center gap-1">
                            <span class="text-xs font-medium px-2 py-0.5 rounded" style="background:{{ $aiClass->suggestedPriority->color }}20;color:{{ $aiClass->suggestedPriority->color }}">{{ $aiClass->suggestedPriority->name }}</span>
                            <span class="text-xs text-gray-400">{{ $aiClass->priority_confidence }}%</span>
                        </div>
                    </div>
                    @endif
                    @if(!$aiClass->applied)
                    <div class="flex gap-2">
                        <button onclick="aiAccept({{ $aiClass->id }})" class="flex-1 py-1.5 text-xs bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-medium">✓ Aceptar</button>
                        <button onclick="aiReject({{ $aiClass->id }})" class="flex-1 py-1.5 text-xs bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition">✗ Rechazar</button>
                    </div>
                    @else
                    <p class="text-xs text-green-600 text-center">✓ Sugerencia aceptada</p>
                    @endif
                    @if(!empty($aiClass->kb_suggestions))
                    <div class="mt-3 pt-3 border-t border-gray-100">
                        <p class="text-xs font-medium text-gray-700 mb-2">📚 Artículos relacionados:</p>
                        @foreach(array_slice($aiClass->kb_suggestions, 0, 3) as $sug)
                        <a href="{{ $sug['url'] }}" target="_blank" class="block text-xs text-blue-600 hover:text-blue-800 py-0.5 truncate">→ {{ $sug['title'] }}</a>
                        @endforeach
                    </div>
                    @endif
                    @if(!empty($aiClass->keywords_detected))
                    <div class="mt-2 pt-2 border-t border-gray-100">
                        <div class="flex flex-wrap gap-1">
                            @foreach(array_slice($aiClass->keywords_detected, 0, 8) as $kw)
                            <span class="text-xs bg-gray-100 text-gray-400 px-1.5 py-0.5 rounded">{{ $kw }}</span>
                            @endforeach
                        </div>
                    </div>
                    @endif
                </div>
                @endif
{{-- Asignación --}}
        @if(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']))
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-3">Asignar Agente</h3>
            <form method="POST" action="{{ route('tickets.assign', $ticket) }}">
                @csrf @method('PATCH')
                <select name="assignee_id" class="w-full rounded-lg border-gray-300 text-sm mb-3 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">— Sin asignar —</option>
                    @foreach($agents as $agent)
                    <option value="{{ $agent->id }}" {{ $ticket->assignee_id == $agent->id ? 'selected' : '' }}>
                        {{ $agent->name }}
                    </option>
                    @endforeach
                </select>
                <button type="submit"
                        class="w-full py-2 bg-gray-800 text-white text-sm font-medium rounded-lg hover:bg-gray-900 transition">
                    Asignar
                </button>
            </form>
        </div>
        @endif

        {{-- Detalles del ticket --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-4">Detalles</h3>
            <dl class="space-y-3">
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Solicitante</dt>
                    <dd class="mt-1 flex items-center gap-2">
                        <img src="{{ $ticket->requester->avatar_url }}" class="h-6 w-6 rounded-full">
                        <span class="text-sm text-gray-900">{{ $ticket->requester->name }}</span>
                    </dd>
                </div>
                @if($ticket->category)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Categoría</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $ticket->category->name }}</dd>
                </div>
                @endif
                @if($ticket->type)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Tipo</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $ticket->type->name }}</dd>
                </div>
                @endif
                @if($ticket->department)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Departamento</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $ticket->department->name }}</dd>
                </div>
                @endif
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">SLA Respuesta</dt>
                    <dd class="text-sm text-gray-900 mt-1">
                        {{ $ticket->sla_response_due?->format('d/m/y H:i') ?? '—' }}
                    </dd>
                </div>
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">SLA Resolución</dt>
                    <dd class="text-sm text-gray-900 mt-1">
                        {{ $ticket->sla_resolution_due?->format('d/m/y H:i') ?? '—' }}
                    </dd>
                </div>
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Creado</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $ticket->created_at->format('d/m/y H:i') }}</dd>
                </div>
            </dl>
        </div>
    </div>
</div>

<script>
searchTemplates('');
function searchTemplates(q) {
    fetch('/admin/reply-templates/api?q=' + encodeURIComponent(q))
        .then(r => r.json())
        .then(function(data) {
            var list = document.getElementById('template-list');
            if (!list) return;
            if (!data.length) {
                list.innerHTML = '<p class="text-xs text-gray-400 text-center py-2">Sin plantillas</p>';
                return;
            }
            list.innerHTML = data.map(function(t) {
                return '<button type="button" onclick="insertTemplate(' + JSON.stringify(t.body) + ')"'
                     + ' class="w-full text-left px-3 py-2 text-xs rounded-lg hover:bg-blue-50 transition">'
                     + '<span class="font-medium">' + t.name + '</span>'
                     + (t.shortcut ? ' <span class="text-gray-400 font-mono">' + t.shortcut + '</span>' : '')
                     + '</button>';
            }).join('');
        });
}
function insertTemplate(body) {
    var ta = document.querySelector('[name="body"]');
    if (ta) { ta.value = body; ta.focus(); }
}
</script>


<script>
function aiAccept(id) {
    fetch('/ai/feedback/' + id, {
        method: 'POST',
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':document.querySelector('meta[name="csrf-token"]').content},
        body: JSON.stringify({action:'accept'})
    }).then(r=>r.json()).then(d=>{
        if(d.success) document.getElementById('ai-classification-panel').innerHTML='<p class="text-xs text-green-600 text-center py-2">🤖 ✓ Sugerencia aceptada. Modelo reforzado.</p>';
    });
}
function aiReject(id) {
    fetch('/ai/feedback/' + id, {
        method: 'POST',
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':document.querySelector('meta[name="csrf-token"]').content},
        body: JSON.stringify({action:'reject'})
    }).then(r=>r.json()).then(d=>{
        if(d.success) document.getElementById('ai-classification-panel').innerHTML='<p class="text-xs text-gray-400 text-center py-2">Sugerencia descartada</p>';
    });
}
</script>


<script>
function loadAiResponse(ticketId) {
    const btn    = document.getElementById('ai-response-btn');
    const status = document.getElementById('ai-response-status');
    btn.disabled = true;
    status.classList.remove('hidden');
    status.textContent = 'Generando respuesta...';

    fetch('/ai/response/' + ticketId, {
        headers: {'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content}
    })
    .then(r => r.json())
    .then(d => {
        btn.disabled = false;
        status.classList.add('hidden');
        if (d.success) {
            // Insertar en el textarea
            const ta = document.getElementById('comment-body') || document.querySelector('textarea[name="body"]');
            if (ta) {
                ta.value = d.data.body;
                ta.dispatchEvent(new Event('input'));
            }
            // Mostrar panel de confirmación
            showAiResponsePanel(d.data);
        } else {
            status.classList.remove('hidden');
            status.textContent = d.message;
            setTimeout(() => status.classList.add('hidden'), 3000);
        }
    })
    .catch(() => { btn.disabled = false; status.classList.add('hidden'); });
}

function showAiResponsePanel(data) {
    let panel = document.getElementById('ai-response-panel');
    if (!panel) {
        panel = document.createElement('div');
        panel.id = 'ai-response-panel';
        panel.className = 'mt-2 p-3 bg-purple-50 border border-purple-200 rounded-lg text-xs';
        const ta = document.getElementById('comment-body') || document.querySelector('textarea[name="body"]');
        if (ta && ta.parentNode) ta.parentNode.insertBefore(panel, ta.nextSibling);
    }
    panel.innerHTML = `
        <div class="flex items-center justify-between mb-1">
            <span class="font-medium text-purple-700">🤖 Respuesta generada — ${data.template_name}</span>
            <span class="text-purple-500">Confianza: ${data.confidence}%</span>
        </div>
        <p class="text-gray-500">Revisa el texto antes de enviar. Al enviar se contabilizará como aceptada.</p>
    `;
}
</script>


{{-- ═══ JS: Selector de plantillas de respuesta ═══ --}}
<script>
(function () {
    'use strict';

    // ── Datos del ticket actual (inyectados desde Blade) ──────────────────────
    var TICKET_DATA = {
        solicitante : '{{ $ticket->requester->name ?? "" }}',
        ticket      : '{{ $ticket->number ?? "" }}',
        csrfToken   : document.querySelector('meta[name="csrf-token"]')
                      ? document.querySelector('meta[name="csrf-token"]').content
                      : ''
    };

    // ── Reemplazar marcadores {solicitante} y {ticket} ─────────────────────────
    function applyMarkers(text) {
        return text
            .replace(/\{\{\s*solicitante\s*\}\}/gi, TICKET_DATA.solicitante)
            .replace(/\{\{\s*ticket\s*\}\}/gi,      TICKET_DATA.ticket);
    }

    // ── Obtener textarea de respuesta ─────────────────────────────────────────
    function getTextarea() {
        return document.querySelector(
            'textarea[name="body"], textarea[name="reply"], ' +
            'textarea[name="response"], textarea[name="respuesta"], ' +
            'textarea[name="comment"], textarea[name="comentario"]'
        );
    }

    // ── Aplicar plantilla al textarea ─────────────────────────────────────────
    function applyTemplate(templateId, body) {
        var ta = getTextarea();
        if (!ta) {
            console.warn('[App] Textarea de respuesta no encontrado');
            return;
        }

        var processed = applyMarkers(body);
        ta.value = processed;

        // Disparar evento input para Livewire / Alpine
        ta.dispatchEvent(new Event('input',  { bubbles: true }));
        ta.dispatchEvent(new Event('change', { bubbles: true }));

        // Si Livewire v3 está disponible, sincronizar el modelo
        if (window.Livewire) {
            var wireModel = ta.getAttribute('wire:model') ||
                            ta.getAttribute('wire:model.live') ||
                            ta.getAttribute('wire:model.defer');
            if (wireModel) {
                // Livewire v3
                ta.dispatchEvent(new CustomEvent('input', { bubbles: true }));
            }
        }

        ta.focus();
        ta.setSelectionRange(processed.length, processed.length);

        // Incrementar contador uses
        if (templateId) {
            fetch('/reply-templates/' + templateId + '/use', {
                method  : 'POST',
                headers : {
                    'X-CSRF-TOKEN' : TICKET_DATA.csrfToken,
                    'Content-Type' : 'application/json',
                    'Accept'       : 'application/json'
                }
            }).catch(function () { /* silencioso */ });
        }
    }

    // ── Event listener: cambio en el select ───────────────────────────────────
    document.addEventListener('DOMContentLoaded', function () {

        var sel = document.getElementById('reply-template-select');
        if (sel) {
            sel.addEventListener('change', function () {
                var opt = this.options[this.selectedIndex];
                if (!opt || !opt.value) return;

                var body = opt.getAttribute('data-body') || '';
                applyTemplate(opt.value, body);

                // Resetear el select a la opción en blanco
                this.value = '';
            });
        }

        // ── Soporte de shortcuts: escribir /saludo en textarea ────────────────
        // Recoge todos los shortcuts del select al cargar
        var shortcuts = {};
        if (sel) {
            Array.from(sel.options).forEach(function (opt) {
                var sc = opt.getAttribute('data-shortcut');
                if (sc) shortcuts[sc.toLowerCase()] = {
                    id   : opt.value,
                    body : opt.getAttribute('data-body') || ''
                };
            });
        }

        // Detectar shortcut en el textarea al hacer espacio o Enter
        var ta = getTextarea();
        if (ta && Object.keys(shortcuts).length > 0) {
            ta.addEventListener('input', function () {
                var val = this.value.trim().toLowerCase();
                if (shortcuts[val]) {
                    applyTemplate(shortcuts[val].id, shortcuts[val].body);
                }
            });
        }

    });

})();
</script>

@endsection
