<?php
session_start();
$uploadDir = 'uploads/';

// Eliminar imagen individual
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $fileToDelete = $uploadDir . basename($_GET['delete']);
    if (file_exists($fileToDelete)) {
        unlink($fileToDelete);
        $_SESSION['success_message'] = "Imagen eliminada correctamente.";
        header("Location: ver.php");
        exit();
    }
}

// Obtener todas las imágenes
$images = glob($uploadDir . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
usort($images, function($a, $b) {
    return filemtime($b) - filemtime($a); // Más recientes primero
});

// Configuración de la paginación
$imagesPerPage = 24;
$totalImages = count($images);
$totalPages = ceil($totalImages / $imagesPerPage);
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
if ($page > $totalPages && $totalPages > 0) $page = $totalPages;

$start = ($page - 1) * $imagesPerPage;
$currentImages = array_slice($images, $start, $imagesPerPage);

// Calcular tamaño total de las imágenes actuales
$totalSize = 0;
foreach ($images as $image) {
    $totalSize += filesize($image);
}
$totalSizeMB = round($totalSize / 1048576, 2);
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Galería de Imágenes</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 30px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }
        
        .header img {
            height: 50px;
        }
        
        .header nav a {
            margin-left: 25px;
            text-decoration: none;
            color: #333;
            font-weight: 600;
            transition: color 0.3s;
        }
        
        .header nav a:hover {
            color: #667eea;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: #fff;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        h1 {
            color: #333;
            font-size: 2em;
        }
        
        .stats-bar {
            display: flex;
            gap: 30px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .stat-number {
            font-size: 1.8em;
            font-weight: bold;
        }
        
        .stat-label {
            font-size: 0.9em;
            opacity: 0.9;
        }
        
        .controls {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .button {
            padding: 12px 24px;
            font-size: 15px;
            font-weight: 600;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            text-decoration: none;
            color: #fff;
            transition: all 0.3s;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: inline-block;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
        }
        
        .button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }
        
        .view-toggle {
            display: flex;
            gap: 10px;
        }
        
        .toggle-btn {
            padding: 10px 20px;
            background-color: #f0f0f0;
            border: 2px solid #ddd;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }
        
        .toggle-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: #667eea;
        }
        
        .search-bar {
            width: 100%;
            padding: 15px;
            font-size: 16px;
            border: 2px solid #ddd;
            border-radius: 8px;
            margin-bottom: 20px;
            transition: border-color 0.3s;
        }
        
        .search-bar:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .gallery.list-view {
            grid-template-columns: 1fr;
        }
        
        .image-card {
            background-color: #fff;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            position: relative;
        }
        
        .image-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }
        
        .image-container {
            position: relative;
            width: 100%;
            padding-top: 75%;
            background-color: #f5f5f5;
            overflow: hidden;
        }
        
        .list-view .image-container {
            padding-top: 30%;
        }
        
        .image-container img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        .image-container:hover img {
            transform: scale(1.05);
        }
        
        .image-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .image-container:hover .image-overlay {
            opacity: 1;
        }
        
        .overlay-btn {
            padding: 10px 15px;
            background-color: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .overlay-btn:hover {
            background-color: #fff;
            transform: scale(1.1);
        }
        
        .overlay-btn.delete {
            background-color: rgba(235, 51, 73, 0.9);
            color: white;
        }
        
        .overlay-btn.delete:hover {
            background-color: #eb3349;
        }
        
        .overlay-btn.preview {
            background-color: rgba(102, 126, 234, 0.9);
            color: white;
        }
        
        .overlay-btn.preview:hover {
            background-color: #667eea;
        }
        
        .image-info {
            padding: 15px;
        }
        
        .list-view .image-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .image-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .image-meta {
            font-size: 0.85em;
            color: #666;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 30px;
            flex-wrap: wrap;
        }
        
        .pagination a {
            padding: 10px 15px;
            text-decoration: none;
            color: #333;
            background-color: #fff;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .pagination a.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: #667eea;
        }
        
        .pagination a:hover:not(.active) {
            background-color: #f0f0f0;
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state-icon {
            font-size: 5em;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .empty-state h2 {
            color: #999;
            margin-bottom: 10px;
        }
        
        /* Preview Modal */
        .preview-modal {
            display: none;
            position: fixed;
            z-index: 999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            animation: fadeIn 0.3s;
        }
        
        .preview-modal-content {
            position: relative;
            background-color: #fff;
            margin: 5% auto;
            padding: 0;
            width: 90%;
            max-width: 800px;
            border-radius: 15px;
            box-shadow: 0 10px 50px rgba(0, 0, 0, 0.5);
            max-height: 85vh;
            overflow: hidden;
            animation: slideDown 0.3s;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .preview-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .preview-header h2 {
            margin: 0;
            font-size: 1.5em;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 80%;
        }
        
        .preview-close {
            font-size: 35px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .preview-close:hover {
            transform: rotate(90deg) scale(1.1);
            background-color: rgba(255, 255, 255, 0.3);
        }
        
        .preview-body {
            padding: 30px;
            max-height: calc(85vh - 80px);
            overflow-y: auto;
        }
        
        .preview-body::-webkit-scrollbar {
            width: 8px;
        }
        
        .preview-body::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        .preview-body::-webkit-scrollbar-thumb {
            background: #667eea;
            border-radius: 10px;
        }
        
        .preview-image-container {
            text-align: center;
            margin-bottom: 25px;
            background-color: #f5f5f5;
            border-radius: 10px;
            padding: 20px;
        }
        
        .preview-image {
            max-width: 100%;
            max-height: 400px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .preview-details {
            background-color: #f9f9f9;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .preview-detail-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .preview-detail-row:last-child {
            border-bottom: none;
        }
        
        .preview-detail-label {
            font-weight: 600;
            color: #555;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .preview-detail-value {
            color: #333;
            font-weight: 500;
        }
        
        .preview-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .preview-btn {
            padding: 12px 30px;
            font-size: 15px;
            font-weight: 600;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .preview-btn-download {
            background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
            color: white;
        }
        
        .preview-btn-delete {
            background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
            color: white;
        }
        
        .preview-btn-fullscreen {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .preview-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* Fullscreen Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.95);
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            position: relative;
            margin: auto;
            padding: 20px;
            width: 90%;
            max-width: 1200px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .modal-image {
            max-width: 100%;
            max-height: 70vh;
            object-fit: contain;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
            margin-bottom: 20px;
            cursor: zoom-in;
            transition: transform 0.3s ease;
        }
        
        .modal-image.zoomed {
            cursor: zoom-out;
            max-width: none;
            max-height: none;
            transform-origin: center center;
        }
        
        .modal-image-container {
            position: relative;
            overflow: auto;
            max-width: 100%;
            max-height: 70vh;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-image-container::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }
        
        .modal-image-container::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
        }
        
        .modal-image-container::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 10px;
        }
        
        .modal-image-container::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }
        
        .modal-close {
            position: absolute;
            top: 30px;
            right: 40px;
            font-size: 40px;
            font-weight: bold;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            z-index: 1001;
            background: rgba(0, 0, 0, 0.5);
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
        }
        
        .modal-close:hover {
            transform: scale(1.2);
            background: rgba(102, 126, 234, 0.8);
        }
        
        .modal-zoom-controls {
            position: absolute;
            top: 30px;
            left: 40px;
            display: flex;
            gap: 10px;
            z-index: 1001;
        }
        
        .zoom-btn {
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .zoom-btn:hover {
            background: rgba(102, 126, 234, 0.8);
            transform: scale(1.1);
        }
        
        .zoom-level {
            background: rgba(0, 0, 0, 0.5);
            color: white;
            padding: 10px 15px;
            border-radius: 25px;
            font-weight: 600;
            display: flex;
            align-items: center;
            min-width: 70px;
            justify-content: center;
        }
        
        .modal-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-size: 50px;
            color: white;
            cursor: pointer;
            padding: 20px;
            user-select: none;
            transition: all 0.3s;
            z-index: 1001;
        }
        
        .modal-nav:hover {
            color: #667eea;
            transform: translateY(-50%) scale(1.2);
        }
        
        .modal-prev {
            left: 20px;
        }
        
        .modal-next {
            right: 20px;
        }
        
        .modal-info {
            color: white;
            text-align: center;
            margin-bottom: 15px;
        }
        
        .modal-thumbnails {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            max-width: 90%;
            padding: 10px 0;
            justify-content: center;
        }
        
        .modal-thumbnails::-webkit-scrollbar {
            height: 8px;
        }
        
        .modal-thumbnails::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
        }
        
        .modal-thumbnails::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 10px;
        }
        
        .modal-thumbnails::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }
        
        .modal-thumb {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            border: 3px solid transparent;
            flex-shrink: 0;
        }
        
        .modal-thumb:hover {
            transform: scale(1.1);
            border-color: rgba(255, 255, 255, 0.5);
        }
        
        .modal-thumb.active {
            border-color: #667eea;
            transform: scale(1.15);
            box-shadow: 0 0 20px rgba(102, 126, 234, 0.8);
        }
        
        .message {
            margin: 0 0 20px 0;
            padding: 15px 20px;
            border-radius: 8px;
            text-align: center;
            font-weight: 500;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            .gallery {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 15px;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .stats-bar {
                width: 100%;
                justify-content: space-around;
            }
            
            .preview-modal-content {
                width: 95%;
                margin: 10% auto;
            }
            
            .preview-header h2 {
                font-size: 1.2em;
            }
            
            .preview-body {
                padding: 20px;
            }
            
            .preview-image {
                max-height: 250px;
            }
            
            .preview-actions {
                flex-direction: column;
            }
            
            .preview-btn {
                width: 100%;
                justify-content: center;
            }
            
            .modal-zoom-controls {
                left: 10px;
                top: 80px;
                flex-direction: column;
            }
            
            .zoom-btn {
                width: 40px;
                height: 40px;
                font-size: 20px;
            }
            
            .zoom-level {
                font-size: 12px;
                padding: 8px 10px;
                min-width: 50px;
            }
            
            .modal-close {
                width: 40px;
                height: 40px;
                font-size: 30px;
                right: 10px;
                top: 10px;
            }
            
            .modal-thumb {
                width: 60px;
                height: 60px;
            }
            
            .modal-thumbnails {
                max-width: 100%;
                gap: 5px;
            }
            
            h1 {
                font-size: 1.5em;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <img src="http://descubresanmartin.com/images/Desc.SanMartin2.png" alt="Logo">
        <nav>
            <a href="index.php">📤 Subir</a>
            <a href="about.php">ℹ️ Acerca de</a>
            <a href="contact.php">📧 Contacto</a>
        </nav>
    </div>

    <div class="container">
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="message success">
                <?php 
                echo $_SESSION['success_message']; 
                unset($_SESSION['success_message']);
                ?>
            </div>
        <?php endif; ?>
        
        <div class="page-header">
            <h1>🖼️ Galería de Imágenes</h1>
            <div class="stats-bar">
                <div class="stat-item">
                    <div class="stat-number"><?php echo $totalImages; ?></div>
                    <div class="stat-label">Imágenes</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number"><?php echo $totalSizeMB; ?> MB</div>
                    <div class="stat-label">Tamaño Total</div>
                </div>
                <?php if ($totalPages > 1): ?>
                <div class="stat-item">
                    <div class="stat-number"><?php echo $page; ?>/<?php echo $totalPages; ?></div>
                    <div class="stat-label">Página</div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="controls">
            <a href="index.php" class="button btn-primary">⬅️ Volver a Subir</a>
            
            <div class="view-toggle">
                <button class="toggle-btn active" onclick="setView('grid')" id="grid-btn">
                    🔲 Cuadrícula
                </button>
                <button class="toggle-btn" onclick="setView('list')" id="list-btn">
                    📋 Lista
                </button>
            </div>
        </div>

        <input type="text" class="search-bar" id="search-bar" placeholder="🔍 Buscar imágenes por nombre..." onkeyup="filterImages()">

        <?php if ($totalImages > 0): ?>
            <div class="gallery" id="gallery">
                <?php foreach ($currentImages as $index => $image): 
                    $filename = basename($image);
                    $filesize = round(filesize($image) / 1024, 2);
                    $dimensions = getimagesize($image);
                    $width = $dimensions[0];
                    $height = $dimensions[1];
                    $date = date("d/m/Y H:i", filemtime($image));
                    $globalIndex = $start + $index;
                ?>
                    <div class="image-card" data-filename="<?php echo strtolower($filename); ?>">
                        <div class="image-container">
                            <img src="<?php echo $image; ?>" 
                                 alt="<?php echo $filename; ?>"
                                 onclick="openModal(<?php echo $globalIndex; ?>)"
                                 loading="lazy">
                            <div class="image-overlay">
                                <button class="overlay-btn preview" onclick="openPreview(<?php echo $globalIndex; ?>); event.stopPropagation();">
                                    👁️ Vista Previa
                                </button>
                                <button class="overlay-btn" onclick="downloadImage('<?php echo $image; ?>', '<?php echo $filename; ?>'); event.stopPropagation();">
                                    💾 Descargar
                                </button>
                                <button class="overlay-btn delete" onclick="deleteImage('<?php echo $filename; ?>'); event.stopPropagation();">
                                    🗑️ Eliminar
                                </button>
                            </div>
                        </div>
                        <div class="image-info">
                            <div class="image-name" title="<?php echo $filename; ?>">
                                <?php echo $filename; ?>
                            </div>
                            <div class="image-meta">
                                <?php echo $width; ?>x<?php echo $height; ?> • <?php echo $filesize; ?> KB • <?php echo $date; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>">⬅️ Anterior</a>
                    <?php endif; ?>
                    
                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    
                    if ($startPage > 1): ?>
                        <a href="?page=1">1</a>
                        <?php if ($startPage > 2): ?>
                            <span style="padding: 10px;">...</span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a href="?page=<?php echo $i; ?>" class="<?php if ($i == $page) echo 'active'; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                            <span style="padding: 10px;">...</span>
                        <?php endif; ?>
                        <a href="?page=<?php echo $totalPages; ?>"><?php echo $totalPages; ?></a>
                    <?php endif; ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>">Siguiente ➡️</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="empty-state">
                <div class="empty-state-icon">📁</div>
                <h2>No hay imágenes para mostrar</h2>
                <p>Sube algunas imágenes para verlas aquí</p>
                <a href="index.php" class="button btn-success" style="margin-top: 20px;">
                    📤 Subir Imágenes
                </a>
            </div>
        <?php endif; ?>
    </div>

    <!-- Preview Modal -->
    <div id="previewModal" class="preview-modal" onclick="closePreview(event)">
        <div class="preview-modal-content" onclick="event.stopPropagation()">
            <div class="preview-header">
                <h2 id="previewTitle">Vista Previa</h2>
                <span class="preview-close" onclick="closePreview()">&times;</span>
            </div>
            <div class="preview-body">
                <div class="preview-image-container">
                    <img id="previewImage" class="preview-image" src="" alt="Vista Previa">
                </div>
                <div class="preview-details">
                    <div class="preview-detail-row">
                        <span class="preview-detail-label">📝 Nombre:</span>
                        <span class="preview-detail-value" id="previewName"></span>
                    </div>
                    <div class="preview-detail-row">
                        <span class="preview-detail-label">📐 Dimensiones:</span>
                        <span class="preview-detail-value" id="previewDimensions"></span>
                    </div>
                    <div class="preview-detail-row">
                        <span class="preview-detail-label">💾 Tamaño:</span>
                        <span class="preview-detail-value" id="previewSize"></span>
                    </div>
                    <div class="preview-detail-row">
                        <span class="preview-detail-label">📅 Fecha:</span>
                        <span class="preview-detail-value" id="previewDate"></span>
                    </div>
                    <div class="preview-detail-row">
                        <span class="preview-detail-label">🔢 Formato:</span>
                        <span class="preview-detail-value" id="previewFormat"></span>
                    </div>
                </div>
                <div class="preview-actions">
                    <button class="preview-btn preview-btn-download" onclick="downloadCurrentPreview()">
                        💾 Descargar
                    </button>
                    <button class="preview-btn preview-btn-fullscreen" onclick="openFullscreenFromPreview()">
                        🖼️ Pantalla Completa
                    </button>
                    <button class="preview-btn preview-btn-delete" onclick="deleteCurrentPreview()">
                        🗑️ Eliminar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Fullscreen Modal -->
    <div id="imageModal" class="modal" onclick="closeModal(event)">
        <span class="modal-close" onclick="closeModal()">&times;</span>
        
        <div class="modal-zoom-controls">
            <button class="zoom-btn" onclick="zoomIn(); event.stopPropagation();" title="Acercar">+</button>
            <div class="zoom-level" id="zoomLevel">100%</div>
            <button class="zoom-btn" onclick="zoomOut(); event.stopPropagation();" title="Alejar">−</button>
            <button class="zoom-btn" onclick="resetZoom(); event.stopPropagation();" title="Restablecer">⟲</button>
        </div>
        
        <div class="modal-nav modal-prev" onclick="changeImage(-1); event.stopPropagation();">❮</div>
        <div class="modal-nav modal-next" onclick="changeImage(1); event.stopPropagation();">❯</div>
        <div class="modal-content" onclick="event.stopPropagation()">
            <div class="modal-info" id="modalInfo"></div>
            <div class="modal-image-container" id="modalImageContainer">
                <img class="modal-image" id="modalImage" src="">
            </div>
            <div class="modal-thumbnails" id="modalThumbnails"></div>
        </div>
    </div>

    <script>
        const allImages = <?php echo json_encode(array_values($images)); ?>;
        const allFilenames = <?php echo json_encode(array_map('basename', $images)); ?>;
        const allImageData = <?php 
            $imageData = [];
            foreach ($images as $img) {
                $filename = basename($img);
                $filesize = round(filesize($img) / 1024, 2);
                $dimensions = getimagesize($img);
                $imageData[] = [
                    'path' => $img,
                    'filename' => $filename,
                    'width' => $dimensions[0],
                    'height' => $dimensions[1],
                    'size' => $filesize,
                    'date' => date("d/m/Y H:i", filemtime($img)),
                    'format' => strtoupper(pathinfo($filename, PATHINFO_EXTENSION))
                ];
            }
            echo json_encode($imageData);
        ?>;
        
        let currentImageIndex = 0;
        let currentZoom = 1;
        let isDragging = false;
        let startX, startY, scrollLeft, scrollTop;

        function setView(view) {
            const gallery = document.getElementById('gallery');
            const gridBtn = document.getElementById('grid-btn');
            const listBtn = document.getElementById('list-btn');
            
            if (view === 'list') {
                gallery.classList.add('list-view');
                gridBtn.classList.remove('active');
                listBtn.classList.add('active');
            } else {
                gallery.classList.remove('list-view');
                gridBtn.classList.add('active');
                listBtn.classList.remove('active');
            }
        }

        function filterImages() {
            const searchValue = document.getElementById('search-bar').value.toLowerCase();
            const cards = document.querySelectorAll('.image-card');
            
            cards.forEach(card => {
                const filename = card.getAttribute('data-filename');
                if (filename.includes(searchValue)) {
                    card.style.display = '';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        // Preview Modal Functions
        function openPreview(index) {
            currentImageIndex = index;
            const imageData = allImageData[index];
            const previewModal = document.getElementById('previewModal');
            
            document.getElementById('previewImage').src = imageData.path;
            document.getElementById('previewTitle').textContent = imageData.filename;
            document.getElementById('previewName').textContent = imageData.filename;
            document.getElementById('previewDimensions').textContent = imageData.width + ' x ' + imageData.height + ' px';
            document.getElementById('previewSize').textContent = imageData.size + ' KB';
            document.getElementById('previewDate').textContent = imageData.date;
            document.getElementById('previewFormat').textContent = imageData.format;
            
            previewModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        function closePreview(event) {
            if (!event || event.target.id === 'previewModal') {
                document.getElementById('previewModal').style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        }

        function downloadCurrentPreview() {
            const imageData = allImageData[currentImageIndex];
            downloadImage(imageData.path, imageData.filename);
        }

        function openFullscreenFromPreview() {
            closePreview();
            openModal(currentImageIndex);
        }

        function deleteCurrentPreview() {
            const imageData = allImageData[currentImageIndex];
            deleteImage(imageData.filename);
        }

        // Fullscreen Modal Functions
        function openModal(index) {
            currentImageIndex = index;
            currentZoom = 1;
            const modal = document.getElementById('imageModal');
            const modalImage = document.getElementById('modalImage');
            const modalInfo = document.getElementById('modalInfo');
            const modalThumbnails = document.getElementById('modalThumbnails');
            
            modalImage.src = allImages[index];
            modalImage.style.transform = 'scale(1)';
            modalImage.classList.remove('zoomed');
            updateZoomLevel();
            
            modalInfo.innerHTML = `<strong>${allFilenames[index]}</strong><br>Imagen ${index + 1} de ${allImages.length}`;
            
            // Generar miniaturas
            modalThumbnails.innerHTML = '';
            allImages.forEach((img, i) => {
                const thumb = document.createElement('img');
                thumb.src = img;
                thumb.className = 'modal-thumb' + (i === index ? ' active' : '');
                thumb.onclick = function(e) {
                    e.stopPropagation();
                    openModal(i);
                };
                modalThumbnails.appendChild(thumb);
            });
            
            // Scroll a la miniatura activa
            setTimeout(() => {
                const activeThumb = modalThumbnails.querySelector('.modal-thumb.active');
                if (activeThumb) {
                    activeThumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
                }
            }, 100);
            
            modal.style.display = 'block';
            document.body.style.overflow = 'hidden';
            
            // Configurar arrastre para zoom
            setupImageDrag();
        }

        function closeModal(event) {
            if (!event || event.target.id === 'imageModal') {
                document.getElementById('imageModal').style.display = 'none';
                document.body.style.overflow = 'auto';
                currentZoom = 1;
            }
        }

        function changeImage(direction) {
            currentImageIndex += direction;
            
            if (currentImageIndex < 0) {
                currentImageIndex = allImages.length - 1;
            } else if (currentImageIndex >= allImages.length) {
                currentImageIndex = 0;
            }
            
            currentZoom = 1;
            const modalImage = document.getElementById('modalImage');
            const modalInfo = document.getElementById('modalInfo');
            const modalThumbnails = document.getElementById('modalThumbnails');
            const modalImageContainer = document.getElementById('modalImageContainer');
            
            modalImage.src = allImages[currentImageIndex];
            modalImage.style.transform = 'scale(1)';
            modalImage.classList.remove('zoomed');
            modalImageContainer.scrollLeft = 0;
            modalImageContainer.scrollTop = 0;
            updateZoomLevel();
            
            modalInfo.innerHTML = `<strong>${allFilenames[currentImageIndex]}</strong><br>Imagen ${currentImageIndex + 1} de ${allImages.length}`;
            
            // Actualizar miniatura activa
            const thumbs = modalThumbnails.querySelectorAll('.modal-thumb');
            thumbs.forEach((thumb, i) => {
                if (i === currentImageIndex) {
                    thumb.classList.add('active');
                    thumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
                } else {
                    thumb.classList.remove('active');
                }
            });
        }

        function zoomIn() {
            currentZoom = Math.min(currentZoom + 0.25, 4);
            applyZoom();
        }

        function zoomOut() {
            currentZoom = Math.max(currentZoom - 0.25, 0.5);
            applyZoom();
        }

        function resetZoom() {
            currentZoom = 1;
            applyZoom();
            const modalImageContainer = document.getElementById('modalImageContainer');
            modalImageContainer.scrollLeft = 0;
            modalImageContainer.scrollTop = 0;
        }

        function applyZoom() {
            const modalImage = document.getElementById('modalImage');
            modalImage.style.transform = `scale(${currentZoom})`;
            
            if (currentZoom > 1) {
                modalImage.classList.add('zoomed');
            } else {
                modalImage.classList.remove('zoomed');
            }
            
            updateZoomLevel();
        }

        function updateZoomLevel() {
            document.getElementById('zoomLevel').textContent = Math.round(currentZoom * 100) + '%';
        }

        function setupImageDrag() {
            const modalImageContainer = document.getElementById('modalImageContainer');
            const modalImage = document.getElementById('modalImage');
            
            // Click en la imagen para hacer zoom
            modalImage.onclick = function(e) {
                e.stopPropagation();
                if (currentZoom === 1) {
                    currentZoom = 2;
                } else {
                    currentZoom = 1;
                }
                applyZoom();
            };
            
            // Arrastrar cuando hay zoom
            modalImageContainer.onmousedown = function(e) {
                if (currentZoom > 1) {
                    isDragging = true;
                    modalImageContainer.style.cursor = 'grabbing';
                    startX = e.pageX - modalImageContainer.offsetLeft;
                    startY = e.pageY - modalImageContainer.offsetTop;
                    scrollLeft = modalImageContainer.scrollLeft;
                    scrollTop = modalImageContainer.scrollTop;
                }
            };

            modalImageContainer.onmouseleave = function() {
                isDragging = false;
                modalImageContainer.style.cursor = currentZoom > 1 ? 'grab' : 'auto';
            };

            modalImageContainer.onmouseup = function() {
                isDragging = false;
                modalImageContainer.style.cursor = currentZoom > 1 ? 'grab' : 'auto';
            };

            modalImageContainer.onmousemove = function(e) {
                if (!isDragging) return;
                e.preventDefault();
                const x = e.pageX - modalImageContainer.offsetLeft;
                const y = e.pageY - modalImageContainer.offsetTop;
                const walkX = (x - startX) * 2;
                const walkY = (y - startY) * 2;
                modalImageContainer.scrollLeft = scrollLeft - walkX;
                modalImageContainer.scrollTop = scrollTop - walkY;
            };
            
            // Zoom con la rueda del mouse
            modalImageContainer.onwheel = function(e) {
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault();
                    if (e.deltaY < 0) {
                        zoomIn();
                    } else {
                        zoomOut();
                    }
                }
            };
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            const modal = document.getElementById('imageModal');
            const previewModal = document.getElementById('previewModal');
            
            if (modal.style.display === 'block') {
                if (e.key === 'Escape') {
                    closeModal();
                } else if (e.key === 'ArrowLeft') {
                    changeImage(-1);
                } else if (e.key === 'ArrowRight') {
                    changeImage(1);
                } else if (e.key === '+' || e.key === '=') {
                    zoomIn();
                } else if (e.key === '-' || e.key === '_') {
                    zoomOut();
                } else if (e.key === '0') {
                    resetZoom();
                }
            }
            
            if (previewModal.style.display === 'block') {
                if (e.key === 'Escape') {
                    closePreview();
                }
            }
        });

        function downloadImage(url, filename) {
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        function deleteImage(filename) {
            if (confirm('¿Estás seguro de que deseas eliminar esta imagen?')) {
                window.location.href = '?delete=' + encodeURIComponent(filename);
            }
        }
    </script>
</body>
</html>