@extends('layouts.app')
@section('title','API Docs')
@section('content')
<div class="mb-6 flex items-center justify-between">
    <div>
        <h1 class="text-2xl font-bold text-gray-900">{{ config("app.name", "Service Desk") }} API v1</h1>
        <p class="text-sm text-gray-500 mt-1">REST · Bearer Token (Sanctum) · JSON</p>
    </div>
    <code class="text-xs bg-gray-100 px-3 py-1.5 rounded-lg text-blue-700 font-mono">{{ url('/api/v1') }}</code>
</div>

<div class="grid grid-cols-3 gap-4 mb-6">
    @foreach([['Formato','JSON (application/json)','📄'],['Autenticación','Bearer Token — Sanctum','🔐'],['Rate Limit','60/min general · 10/min login','⏱️']] as [$t,$v,$i])
    <div class="bg-white rounded-xl border border-gray-200 p-4">
        <p class="text-xs text-gray-500 uppercase mb-1">{{ $i }} {{ $t }}</p>
        <p class="text-sm font-medium">{{ $v }}</p>
    </div>
    @endforeach
</div>

<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
    <h2 class="text-base font-semibold mb-4">🔐 Autenticación</h2>
    @foreach([['POST','auth/login','Obtener token (sin auth requerida)',false],['GET','auth/me','Perfil del usuario autenticado',true],['GET','auth/tokens','Tokens activos',true],['POST','auth/logout','Cerrar sesión actual',true],['POST','auth/logout-all','Cerrar todas las sesiones',true]] as [$m,$p,$d,$pr])
    @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>$pr])
    @endforeach
    <div class="mt-4 grid grid-cols-2 gap-3">
        <div><p class="text-xs text-gray-400 mb-1">Request</p>
        <pre class="bg-gray-900 text-green-300 text-xs p-3 rounded-lg">POST /api/v1/auth/login
{
  "email": "admin@nexus.com",
  "password": "contraseña",
  "device_name": "mi-app"
}</pre></div>
        <div><p class="text-xs text-gray-400 mb-1">Response 200</p>
        <pre class="bg-gray-900 text-green-300 text-xs p-3 rounded-lg">{
  "success": true,
  "data": {
    "token": "1|abc123xyz...",
    "token_type": "Bearer",
    "user": {"id":1,"name":"Admin"}
  }
}</pre></div>
    </div>
    <div class="mt-3 p-3 bg-blue-50 rounded-lg text-xs text-blue-700">
        Incluye en cada solicitud: <code class="font-mono font-bold">Authorization: Bearer {token}</code>
    </div>
</div>

<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-5">
    <h2 class="text-base font-semibold mb-4">🎫 Tickets</h2>
    @foreach([['GET','tickets/stats','Estadísticas en tiempo real (agentes+)'],['GET','tickets','Listar con filtros y paginación'],['POST','tickets','Crear ticket'],['GET','tickets/{id}','Detalle con historial y comentarios'],['PATCH','tickets/{id}','Actualizar estado / prioridad / agente'],['POST','tickets/{id}/comments','Agregar comentario']] as [$m,$p,$d])
    @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>true])
    @endforeach
    <details class="mt-3"><summary class="text-xs text-blue-600 cursor-pointer">Ver filtros disponibles</summary>
    <div class="mt-2 grid grid-cols-2 gap-1 text-xs bg-gray-50 rounded-lg p-3">
        @foreach(['status → ID del estado','priority → ID de prioridad','category → ID de categoría','assignee → ID del agente','q → búsqueda en título y número','from → fecha inicio (Y-m-d)','to → fecha fin (Y-m-d)','sort → created_at|updated_at|priority_id','direction → asc|desc','per_page → máx 100 (default 20)'] as $f)
        <p><code class="text-blue-600 font-mono">{{ explode(' → ',$f)[0] }}</code> — {{ explode(' → ',$f)[1] }}</p>
        @endforeach
    </div></details>
</div>

<div class="grid grid-cols-2 gap-5 mb-5">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-base font-semibold mb-4">🖥️ Activos (CMDB)</h2>
        @foreach([['GET','assets','Listar con filtros'],['GET','assets/by-code/{code}','Buscar por código (QR)'],['GET','assets/{id}','Detalle del activo']] as [$m,$p,$d])
        @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>true])
        @endforeach
    </div>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-base font-semibold mb-4">📚 Base de Conocimiento</h2>
        @foreach([['GET','kb/categories','Categorías con conteo'],['GET','kb/search?q=texto','Búsqueda full-text'],['GET','kb','Artículos publicados'],['GET','kb/{slug}','Detalle del artículo']] as [$m,$p,$d])
        @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>true])
        @endforeach
    </div>
</div>

<div class="grid grid-cols-2 gap-5 mb-5">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-base font-semibold mb-4">👥 Usuarios</h2>
        @foreach([['GET','users/agents','Agentes con carga de tickets'],['GET','users','Lista completa (admin+)']] as [$m,$p,$d])
        @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>true])
        @endforeach
    </div>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-base font-semibold mb-4">📊 Reportes</h2>
        @foreach([['GET','reports/summary','KPIs del período (from/to)'],['GET','reports/sla','Cumplimiento SLA por prioridad']] as [$m,$p,$d])
        @include('api._endpoint',['method'=>$m,'path'=>$p,'desc'=>$d,'protected'=>true])
        @endforeach
    </div>
</div>

<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
    <h2 class="text-base font-semibold mb-4">⏱️ Rate Limiting · ⚠️ Errores</h2>
    <div class="grid grid-cols-2 gap-5">
        <div>
            <table class="min-w-full text-xs">
                <thead><tr class="bg-gray-50"><th class="p-2 text-left">Tier</th><th class="p-2">Límite</th><th class="p-2 text-left">Aplica a</th></tr></thead>
                <tbody class="divide-y divide-gray-100">
                    <tr><td class="p-2 font-mono">api</td><td class="p-2 text-center">60/min</td><td class="p-2">Todos los endpoints</td></tr>
                    <tr><td class="p-2 font-mono">strict</td><td class="p-2 text-center">20/min</td><td class="p-2">Reportes</td></tr>
                    <tr><td class="p-2 font-mono">auth</td><td class="p-2 text-center">10/min</td><td class="p-2">Login (por IP)</td></tr>
                </tbody>
            </table>
        </div>
        <div class="space-y-1 text-xs">
            @foreach(['200 OK — Solicitud exitosa','201 Created — Recurso creado','401 Unauthorized — Token inválido o ausente','403 Forbidden — Sin permisos para el recurso','422 Validation Error — Datos de entrada inválidos','429 Too Many Requests — Rate limit superado','500 Server Error — Error interno del servidor'] as $e)
            @php [$code,$msg] = explode(' ',$e,2); @endphp
            <p><code class="font-mono font-bold text-blue-600">{{ $code }}</code> {{ $msg }}</p>
            @endforeach
        </div>
    </div>
</div>
@endsection
