@extends('layouts.portal')
@section('title', $ticket->number)
@section('content')

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

{{-- Header ticket --}}
<div class="flex items-center gap-3 mb-5">
    <a href="{{ route('portal.index') }}"
       class="w-9 h-9 flex items-center justify-center rounded-full bg-white border border-gray-200 text-gray-500 shadow-sm flex-shrink-0">
        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5">
            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
        </svg>
    </a>
    <div class="flex-1 min-w-0">
        <div class="flex items-center gap-2 flex-wrap">
            <span class="font-mono font-bold text-blue-600 text-sm">{{ $ticket->number }}</span>
            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  style="background-color: {{ $ticket->status->color }}20; color: {{ $ticket->status->color }}">
                {{ $ticket->status->name }}
            </span>
        </div>
        <p class="text-xs text-gray-400 mt-0.5">{{ $ticket->created_at->format('d/m/Y H:i') }}</p>
    </div>
</div>

{{-- Encuesta satisfacción --}}
@if($ticket->status->is_final && !$ticket->satisfaction_score)
<div class="bg-blue-50 border border-blue-200 rounded-2xl p-4 mb-4">
    <h3 class="text-sm font-semibold text-blue-900 mb-3">¿Cómo fue la atención?</h3>
    <form method="POST" action="{{ route('portal.satisfaction', $ticket) }}">
        @csrf
        <div class="flex gap-2 mb-3">
            @for($i = 1; $i <= 5; $i++)
            <button type="button"
                    onclick="document.getElementById('scoreInput').value='{{ $i }}';
                             document.querySelectorAll('.star-btn').forEach((b,j) => {
                                 b.classList.toggle('bg-yellow-400', j < {{ $i }});
                                 b.classList.toggle('bg-gray-100', j >= {{ $i }});
                             });"
                    class="star-btn flex-1 py-2 text-base bg-gray-100 rounded-xl transition">
                {{ $i }}⭐
            </button>
            @endfor
        </div>
        <input type="hidden" name="score" id="scoreInput" value="">
        <textarea name="comment" rows="2" placeholder="Comentario opcional..."
                  class="w-full rounded-xl border-gray-200 text-sm px-3 py-2 mb-3 bg-white"></textarea>
        <button type="submit"
                class="w-full py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl">
            Enviar calificación
        </button>
    </form>
</div>
@elseif($ticket->satisfaction_score)
<div class="bg-green-50 border border-green-200 rounded-2xl p-3 mb-4 flex items-center gap-2 text-sm text-green-800">
    <span>✓</span> Calificaste esta atención con <strong>{{ $ticket->satisfaction_score }}/5</strong> estrellas.
</div>
@endif

{{-- Descripción --}}
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
    <h2 class="text-base font-bold text-gray-900 mb-2">{{ $ticket->title }}</h2>
    <p class="text-sm text-gray-600 whitespace-pre-wrap leading-relaxed">{{ $ticket->description }}</p>
    <div class="flex items-center gap-3 mt-3 pt-3 border-t border-gray-50 text-xs text-gray-400 flex-wrap">
        <span style="color: {{ $ticket->priority->color }}" class="font-medium">
            ● {{ $ticket->priority->name }}
        </span>
        @if($ticket->category)
        <span>{{ $ticket->category->name }}</span>
        @endif
        @if($ticket->sla_resolution_due && !$ticket->status->is_final)
        <span>SLA: {{ $ticket->sla_remaining }}</span>
        @endif
    </div>
</div>

{{-- Adjuntos del ticket --}}
@php $ticketAttachments = $ticket->attachments->whereNull('comment_id'); @endphp
@if($ticketAttachments->count())
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
    <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Archivos adjuntos</h3>
    <div class="space-y-2">
        @foreach($ticketAttachments as $att)
        <a href="{{ asset('storage/' . $att->path) }}" target="_blank"
           class="flex items-center gap-3 p-3 rounded-xl bg-gray-50 hover:bg-blue-50 transition">
            <div class="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0">
                @if(str_contains($att->mime_type, 'image'))
                    <svg class="h-4 w-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                @else
                    <svg class="h-4 w-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"/></svg>
                @endif
            </div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-800 truncate">{{ $att->original_name }}</p>
                <p class="text-xs text-gray-400">{{ $att->human_size }}</p>
            </div>
            <svg class="h-4 w-4 text-gray-300 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
            </svg>
        </a>
        @endforeach
    </div>
</div>
@endif

{{-- Conversación --}}
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm mb-4">
    <div class="px-4 py-3 border-b border-gray-50">
        <h3 class="text-sm font-semibold text-gray-700">Conversación</h3>
    </div>

    <div class="divide-y divide-gray-50">
        @forelse($ticket->comments->where('is_internal', false) as $comment)
        <div class="px-4 py-4 {{ $comment->user_id === auth()->id() ? '' : 'bg-gray-50' }}">
            <div class="flex items-center gap-2 mb-2">
                <div class="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0
                    {{ $comment->user_id === auth()->id() ? 'bg-blue-100 text-blue-700' : 'bg-gray-200 text-gray-600' }}">
                    {{ strtoupper(substr($comment->user->name, 0, 1)) }}
                </div>
                <span class="text-sm font-medium text-gray-800">
                    {{ $comment->user_id === auth()->id() ? 'Tú' : $comment->user->name }}
                </span>
                <span class="text-xs text-gray-400 ml-auto">{{ $comment->created_at->diffForHumans() }}</span>
            </div>
            <p class="text-sm text-gray-700 leading-relaxed pl-9">{{ $comment->body }}</p>

            {{-- Adjuntos del comentario --}}
            @php $commentAtts = $ticket->attachments->where('comment_id', $comment->id); @endphp
            @if($commentAtts->count())
            <div class="pl-9 mt-2 space-y-1">
                @foreach($commentAtts as $att)
                <a href="{{ asset('storage/' . $att->path) }}" target="_blank"
                   class="inline-flex items-center gap-2 text-xs text-blue-600 bg-blue-50 px-3 py-1.5 rounded-lg hover:bg-blue-100 transition">
                    <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"/></svg>
                    {{ $att->original_name }} ({{ $att->human_size }})
                </a>
                @endforeach
            </div>
            @endif
        </div>
        @empty
        <div class="px-4 py-10 text-center text-sm text-gray-400">
            Sin mensajes aún. Puedes escribirnos si tienes más información.
        </div>
        @endforelse
    </div>

    @if(!$ticket->status->is_final)
    <div class="px-4 py-4 border-t border-gray-50 bg-gray-50 rounded-b-2xl">
        <form method="POST" action="{{ route('portal.comment', $ticket) }}" enctype="multipart/form-data">
            @csrf
            <textarea name="body" rows="3"
                      placeholder="Escribe un mensaje o información adicional..."
                      class="w-full rounded-xl border-gray-200 text-sm px-3 py-2.5 mb-3 bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"></textarea>

            {{-- Adjuntar archivo al comentario --}}
            <label class="flex items-center gap-2 text-xs text-gray-500 cursor-pointer mb-3 hover:text-blue-600 transition w-fit">
                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"/>
                </svg>
                <span id="comment-file-label">Adjuntar archivo (opcional)</span>
                <input type="file" name="attachments[]" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.txt,.zip"
                       class="hidden" onchange="document.getElementById('comment-file-label').textContent = this.files.length + ' archivo(s)'">
            </label>

            <button type="submit"
                    class="w-full py-3 bg-blue-600 text-white text-sm font-semibold rounded-xl hover:bg-blue-700 transition">
                Enviar mensaje
            </button>
        </form>
    </div>
    @endif
</div>

@endsection
