@extends('admin.layouts.app')
@section('title', 'Publicaciones')

@section('styles')
<style>
:root { --n-blue:#1a237e; --n-gold:#ffe082; --n-purple:#4527a0; }

/* ── Hero ── */
.not-hero {
    background: linear-gradient(135deg,#0d1b6e 0%,#1a237e 45%,#4527a0 100%);
    border-radius: 20px; padding: 22px 28px;
    display: flex; align-items: center; justify-content: space-between;
    flex-wrap: wrap; gap: 16px; margin-bottom: 24px;
    box-shadow: 0 8px 32px rgba(13,27,110,.25);
}
.not-hero h1 {
    font-size: 1.35rem; font-weight: 800; color: #fff; margin: 0 0 2px;
    display: flex; align-items: center; gap: 10px;
}
.not-hero p { color: rgba(255,255,255,.55); margin: 0; font-size: .83rem; }
.hero-badge {
    background: rgba(255,224,130,.12); border: 1.5px solid rgba(255,224,130,.25);
    border-radius: 12px; padding: 10px 18px; text-align: center;
}
.hero-badge .num  { font-size: 1.6rem; font-weight: 900; color: var(--n-gold); line-height: 1; }
.hero-badge .lbl  { font-size: 10px; color: rgba(255,255,255,.5); font-weight: 700; margin-top: 2px; }

/* ── Stats strip ── */
.not-stats { display: flex; gap: 14px; flex-wrap: wrap; margin-bottom: 22px; }
.stat-card {
    flex: 1; min-width: 120px;
    background: #fff; border-radius: 16px;
    padding: 14px 18px;
    box-shadow: 0 2px 12px rgba(0,0,0,.06);
    border-left: 4px solid transparent;
    transition: transform .2s, box-shadow .2s;
}
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(0,0,0,.1); }
.stat-card .s-num { font-size: 1.5rem; font-weight: 800; }
.stat-card .s-lbl { font-size: 11px; color: #94a3b8; font-weight: 700; margin-top: 2px; }

/* ── Toolbar ── */
.not-toolbar {
    display: flex; gap: 12px; flex-wrap: wrap; align-items: center;
    background: #fff; border-radius: 14px; padding: 14px 18px;
    box-shadow: 0 2px 12px rgba(0,0,0,.05); margin-bottom: 18px;
}
.not-toolbar input[type=text], .not-toolbar select {
    border: 1.5px solid #e2e8f0; border-radius: 10px;
    padding: 9px 14px; font-size: .88rem; color: #334155;
    outline: none; transition: border-color .2s;
}
.not-toolbar input[type=text]:focus, .not-toolbar select:focus { border-color: var(--n-blue); }
.not-toolbar input[type=text] { flex: 1; min-width: 200px; }

/* ── Table card ── */
.not-table-card {
    background: #fff; border-radius: 18px;
    box-shadow: 0 2px 16px rgba(0,0,0,.06); overflow: hidden;
}
.not-table-header {
    background: linear-gradient(135deg,var(--n-blue),var(--n-purple));
    padding: 14px 22px; display: flex; align-items: center;
    justify-content: space-between; gap: 12px; flex-wrap: wrap;
}
.not-table-header span { color: var(--n-gold); font-weight: 800; font-size: .95rem; }
.not-table-header small { color: rgba(255,255,255,.5); font-size: .78rem; font-weight: 600; }

/* ── Table ── */
.tbl-not { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.tbl-not thead th {
    background: #f8faff; color: #64748b; font-size: 11px; font-weight: 800;
    padding: 10px 14px; text-transform: uppercase; letter-spacing: .5px;
    border-bottom: 2px solid #f1f5f9; white-space: nowrap;
}
.tbl-not tbody tr { border-bottom: 1px solid #f8fafc; transition: background .15s; }
.tbl-not tbody tr:hover { background: #f8faff; }
.tbl-not td { padding: 11px 14px; vertical-align: middle; }

/* ── Badges ── */
.tipo-badge {
    padding: 4px 11px; border-radius: 50px; font-size: 11px; font-weight: 800;
    display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
}
.tipo-noticia      { background:#eff6ff; color:#1d4ed8; border:1px solid #bfdbfe; }
.tipo-comunicado   { background:#fdf4ff; color:#7e22ce; border:1px solid #e9d5ff; }
.tipo-convocatoria { background:#fff7ed; color:#c2410c; border:1px solid #fed7aa; }
.tipo-logro        { background:#f0fdf4; color:#15803d; border:1px solid #bbf7d0; }

.st-badge {
    padding: 4px 10px; border-radius: 50px; font-size: 11px; font-weight: 700;
    display: inline-flex; align-items: center; gap: 4px;
}
.st-activo   { background:#dcfce7; color:#15803d; }
.st-inactivo { background:#fee2e2; color:#dc2626; }
.st-dest     { background:#fffbeb; color:#b45309; }

/* ── Img thumb ── */
.thumb-wrap {
    width: 46px; height: 46px; border-radius: 10px; overflow: hidden;
    background: linear-gradient(135deg,#f1f5f9,#e2e8f0);
    display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.thumb-wrap img { width: 46px; height: 46px; object-fit: cover; }

/* ── Botones acción ── */
.act-btn {
    width: 34px; height: 34px; border-radius: 9px; border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center; font-size: 14px;
    transition: all .2s; text-decoration: none;
}
.act-edit   { background:#eff6ff; color:#1d4ed8; }
.act-edit:hover   { background:#dbeafe; }
.act-delete { background:#fef2f2; color:#dc2626; }
.act-delete:hover { background:#fee2e2; }

/* ── Empty state ── */
.empty-not { padding: 64px 20px; text-align: center; }
.empty-not .ic { font-size: 56px; color: #cbd5e1; margin-bottom: 14px; }
.empty-not h3  { font-size: 1.05rem; font-weight: 700; color: #334155; margin-bottom: 6px; }
.empty-not p   { font-size: .88rem; color: #94a3b8; margin-bottom: 20px; }

/* ── popup indicator ── */
.popup-dot {
    display: inline-flex; align-items: center; gap: 4px;
    background: #dcfce7; color: #15803d; padding: 2px 8px;
    border-radius: 50px; font-size: 10px; font-weight: 800;
}
</style>
@endsection

@section('content')

{{-- ═══════ HERO ═══════ --}}
<div class="not-hero">
    <div>
        <h1>
            <div style="width:38px;height:38px;border-radius:12px;background:rgba(255,224,130,.15);border:1.5px solid rgba(255,224,130,.25);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="bi bi-newspaper" style="color:var(--n-gold);font-size:18px;"></i>
            </div>
            Publicaciones
        </h1>
        <p>Gestiona noticias, comunicados, convocatorias y logros</p>
    </div>
    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
        <div class="hero-badge">
            <div class="num">{{ $noticias->count() }}</div>
            <div class="lbl">TOTAL</div>
        </div>
        <div class="hero-badge">
            <div class="num">{{ $noticias->where('activo',true)->count() }}</div>
            <div class="lbl">ACTIVOS</div>
        </div>
        <div class="hero-badge">
            <div class="num">{{ $noticias->where('destacado',true)->count() }}</div>
            <div class="lbl">DESTACADOS</div>
        </div>
        <a href="{{ route('admin.noticias.create') }}"
           style="display:inline-flex;align-items:center;gap:8px;padding:12px 22px;background:linear-gradient(135deg,var(--n-gold),#ffca28);color:var(--n-blue);border-radius:14px;font-weight:800;font-size:.88rem;text-decoration:none;box-shadow:0 4px 16px rgba(255,202,40,.3);transition:all .2s;"
           onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform=''">
            <i class="bi bi-plus-lg"></i> Nueva Publicación
        </a>
    </div>
</div>

{{-- ═══════ STATS ═══════ --}}
@php
    $porTipo = [
        'noticia'      => ['Noticias',      '#1d4ed8', 'bi-newspaper'],
        'comunicado'   => ['Comunicados',   '#7e22ce', 'bi-megaphone-fill'],
        'convocatoria' => ['Convocatorias', '#c2410c', 'bi-file-earmark-text-fill'],
        'logro'        => ['Logros',        '#15803d', 'bi-trophy-fill'],
    ];
@endphp
<div class="not-stats">
    @foreach($porTipo as $tipo => [$label, $color, $icon])
    <div class="stat-card" style="border-left-color:{{ $color }};">
        <div style="display:flex;align-items:center;justify-content:space-between;">
            <div>
                <div class="s-num" style="color:{{ $color }};">{{ $noticias->where('tipo',$tipo)->count() }}</div>
                <div class="s-lbl">{{ strtoupper($label) }}</div>
            </div>
            <div style="width:40px;height:40px;border-radius:12px;background:{{ $color }}18;display:flex;align-items:center;justify-content:center;">
                <i class="bi {{ $icon }}" style="font-size:18px;color:{{ $color }};"></i>
            </div>
        </div>
    </div>
    @endforeach
    <div class="stat-card" style="border-left-color:#f59e0b;">
        <div style="display:flex;align-items:center;justify-content:space-between;">
            <div>
                <div class="s-num" style="color:#f59e0b;">{{ $noticias->where('mostrar_popup',true)->count() }}</div>
                <div class="s-lbl">EN POPUP</div>
            </div>
            <div style="width:40px;height:40px;border-radius:12px;background:#f59e0b18;display:flex;align-items:center;justify-content:center;">
                <i class="bi bi-window-sidebar" style="font-size:18px;color:#f59e0b;"></i>
            </div>
        </div>
    </div>
</div>

{{-- ═══════ TOOLBAR ═══════ --}}
<div class="not-toolbar">
    <input type="text" id="searchNot" placeholder="🔍  Buscar por título..." oninput="filtrarNoticias()">
    <select id="filtroTipo" onchange="filtrarNoticias()">
        <option value="">Todos los tipos</option>
        <option value="noticia">Noticia</option>
        <option value="comunicado">Comunicado</option>
        <option value="convocatoria">Convocatoria</option>
        <option value="logro">Logro</option>
    </select>
    <select id="filtroEstado" onchange="filtrarNoticias()">
        <option value="">Todos los estados</option>
        <option value="activo">Activos</option>
        <option value="inactivo">Inactivos</option>
    </select>
    <div style="margin-left:auto;font-size:.83rem;color:#94a3b8;font-weight:600;">
        <span id="totalVisible">{{ $noticias->count() }}</span> publicación(es)
    </div>
</div>

{{-- ═══════ TABLE ═══════ --}}
<div class="not-table-card">
    <div class="not-table-header">
        <span><i class="bi bi-list-ul me-2"></i>Todas las Publicaciones</span>
        <small id="tblCount">{{ $noticias->count() }} registros</small>
    </div>
    <div style="overflow-x:auto;">
        <table class="tbl-not" id="tablaNoticias">
            <thead>
                <tr>
                    <th style="width:50px;">#</th>
                    <th>Imagen</th>
                    <th>Título</th>
                    <th>Tipo</th>
                    <th>Fecha</th>
                    <th>Destacado</th>
                    <th>Estado</th>
                    <th>Popup</th>
                    <th>Botones</th>
                    <th style="text-align:center;">Acciones</th>
                </tr>
            </thead>
            <tbody>
                @forelse($noticias as $noticia)
                <tr data-titulo="{{ strtolower($noticia->titulo) }}"
                    data-tipo="{{ $noticia->tipo }}"
                    data-estado="{{ $noticia->activo ? 'activo' : 'inactivo' }}">
                    <td><span style="font-size:11px;color:#94a3b8;font-weight:700;">{{ $noticia->id }}</span></td>
                    <td>
                        <div class="thumb-wrap">
                            @if($noticia->imagen)
                            <img src="{{ asset('storage/'.$noticia->imagen) }}" alt="">
                            @else
                            <i class="bi bi-newspaper" style="font-size:20px;color:#94a3b8;"></i>
                            @endif
                        </div>
                    </td>
                    <td style="max-width:240px;">
                        <div style="font-weight:700;color:#1e293b;display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;">
                            {{ $noticia->titulo }}
                        </div>
                        @if($noticia->resumen)
                        <div style="font-size:11px;color:#94a3b8;display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;margin-top:2px;">
                            {{ $noticia->resumen }}
                        </div>
                        @endif
                    </td>
                    <td>
                        @php
                        $tipoClass = match($noticia->tipo) {
                            'noticia'      => 'tipo-noticia',
                            'comunicado'   => 'tipo-comunicado',
                            'convocatoria' => 'tipo-convocatoria',
                            'logro'        => 'tipo-logro',
                            default        => 'tipo-noticia',
                        };
                        $tipoIcon = match($noticia->tipo) {
                            'noticia'      => 'bi-newspaper',
                            'comunicado'   => 'bi-megaphone-fill',
                            'convocatoria' => 'bi-file-earmark-text-fill',
                            'logro'        => 'bi-trophy-fill',
                            default        => 'bi-circle',
                        };
                        @endphp
                        <span class="tipo-badge {{ $tipoClass }}">
                            <i class="bi {{ $tipoIcon }}"></i>
                            {{ $noticia->tipo_label }}
                        </span>
                    </td>
                    <td style="white-space:nowrap;">
                        <div style="font-size:.82rem;color:#475569;font-weight:600;">
                            {{ $noticia->fecha_publicacion->format('d/m/Y') }}
                        </div>
                    </td>
                    <td>
                        @if($noticia->destacado)
                        <span class="st-badge st-dest"><i class="bi bi-star-fill"></i> Sí</span>
                        @else
                        <span style="color:#cbd5e1;font-size:12px;">—</span>
                        @endif
                    </td>
                    <td>
                        <span class="st-badge {{ $noticia->activo ? 'st-activo' : 'st-inactivo' }}">
                            <i class="bi {{ $noticia->activo ? 'bi-check-circle-fill' : 'bi-x-circle-fill' }}"></i>
                            {{ $noticia->activo ? 'Activo' : 'Inactivo' }}
                        </span>
                    </td>
                    <td>
                        @if($noticia->mostrar_popup)
                        <span class="popup-dot"><i class="bi bi-broadcast-pin"></i> ON</span>
                        @else
                        <span style="color:#e2e8f0;font-size:12px;">—</span>
                        @endif
                    </td>
                    <td>
                        @if($noticia->botones && count($noticia->botones) > 0)
                        <div style="display:flex;gap:4px;flex-wrap:wrap;">
                            @foreach($noticia->botones as $btn)
                            <span style="display:inline-block;padding:2px 8px;border-radius:50px;background:{{ $btn['color'] ?? '#1a237e' }};color:#fff;font-size:10px;font-weight:700;white-space:nowrap;">
                                {{ Str::limit($btn['texto'] ?? 'Ver', 12) }}
                            </span>
                            @endforeach
                        </div>
                        @else
                        <span style="color:#e2e8f0;font-size:12px;">—</span>
                        @endif
                    </td>
                    <td>
                        <div style="display:flex;gap:6px;justify-content:center;">
                            <a href="{{ route('admin.noticias.edit', $noticia) }}"
                               class="act-btn act-edit" title="Editar">
                                <i class="bi bi-pencil-fill"></i>
                            </a>
                            <form action="{{ route('admin.noticias.destroy', $noticia) }}" method="POST"
                                  class="form-delete-swal" data-nombre="{{ $noticia->titulo }}">
                                @csrf @method('DELETE')
                                <button type="button" class="act-btn act-delete" title="Eliminar"
                                        onclick="eliminarNoticia(this)">
                                    <i class="bi bi-trash-fill"></i>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="10">
                        <div class="empty-not">
                            <div class="ic"><i class="bi bi-newspaper"></i></div>
                            <h3>Sin publicaciones aún</h3>
                            <p>Crea la primera noticia, comunicado o convocatoria.</p>
                            <a href="{{ route('admin.noticias.create') }}"
                               style="display:inline-flex;align-items:center;gap:8px;padding:12px 24px;background:linear-gradient(135deg,#1a237e,#4527a0);color:#fff;border-radius:14px;font-weight:800;text-decoration:none;box-shadow:0 4px 16px rgba(26,35,126,.25);">
                                <i class="bi bi-plus-lg"></i> Crear primera publicación
                            </a>
                        </div>
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

@endsection

@section('scripts')
<script>
// ── Filtrado ───────────────────────────────────────────
function filtrarNoticias() {
    const q      = document.getElementById('searchNot').value.toLowerCase().trim();
    const tipo   = document.getElementById('filtroTipo').value;
    const estado = document.getElementById('filtroEstado').value;
    const rows   = document.querySelectorAll('#tablaNoticias tbody tr[data-titulo]');
    let visible  = 0;

    rows.forEach(row => {
        const titulo  = row.dataset.titulo  || '';
        const rTipo   = row.dataset.tipo    || '';
        const rEstado = row.dataset.estado  || '';
        const show = (!q || titulo.includes(q))
                  && (!tipo   || rTipo   === tipo)
                  && (!estado || rEstado === estado);
        row.style.display = show ? '' : 'none';
        if (show) visible++;
    });

    document.getElementById('totalVisible').textContent = visible;
    document.getElementById('tblCount').textContent = visible + ' registros';
}

// ── Eliminar con SweetAlert2 ───────────────────────────
function eliminarNoticia(btn) {
    const form   = btn.closest('form');
    const nombre = form.dataset.nombre;
    Swal.fire({
        title: '¿Eliminar publicación?',
        html: `<span style="color:#64748b;">Se eliminará permanentemente:<br><strong>${nombre}</strong></span>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor:  '#64748b',
        confirmButtonText:  '<i class="bi bi-trash-fill"></i> Sí, eliminar',
        cancelButtonText:   'Cancelar',
        reverseButtons: true,
    }).then(r => {
        if (r.isConfirmed) form.submit();
    });
}
</script>
@endsection
