<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Máquina de Donación ADRA</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        /* Variables y estilos base */
        :root {
            --adra-red: #D50032;
            --adra-deep-red: #992A31;
            --adra-cream: #F8F0E4;
            --adra-gold: #C1A01E;
            --adra-pale-blue: #E6F5FA;
            --adra-white: #FFFFFF;
            --text-dark: #333333;
            --text-medium: #666666;
            --text-light: #999999;
            /* NUEVO: Color para fondo de la máquina y bordes camuflados */
            --machine-inner-red: #9A1F28;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            width: 100%;
            overflow: hidden;
            position: fixed;
            /* Forzar fondo oscuro para modo día */
            background-color: #000000;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            /* FONDO NAVIDEÑO CON COLOR DE FONDO DE RESPALDO */
            background: 
                linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), /* Capa oscura para contraste */
                url('fondo-navidad.jpeg') no-repeat center center fixed;
            background-size: cover;
            background-color: #000000; /* Color de respaldo si la imagen no carga */
            color: var(--text-dark);
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: auto;
            -webkit-text-size-adjust: 100%;
            padding: 8px;
            /* Asegurar que el fondo cubra toda el área */
            min-height: 100vh;
            min-width: 100vw;
        }

        /* Forzar modo oscuro en navegadores que lo soporten */
        @media (prefers-color-scheme: light) {
            body {
                background: 
                    linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)),
                    url('fondo-navidad.jpeg') no-repeat center center fixed;
                background-size: cover;
                background-color: #000000;
            }
        }

        .vending-container {
            width: 100%;
            max-width: 500px; /* MÁXIMO ANCHO FIJO */
            height: 100vh;
            max-height: 95vh;
            background: var(--adra-red);
            padding: 10px;
            display: flex;
            flex-direction: column;
            position: relative;
            margin: 0 auto;
            box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
            border-radius: 15px;
            overflow: hidden;
            /* Fondo semitransparente para que se vea bien sobre el fondo navideño */
            background: rgba(213, 0, 50, 0.95);
        }

        .machine-header {
            display: none;
        }

        .items-display {
            /* FONDO INTERNO DE LA MÁQUINA - Rojo oscuro/guinda */
            background: rgba(154, 31, 40, 0.9); /* var(--machine-inner-red) con transparencia */
            border-radius: 0 0 12px 12px;
            padding: 12px;
            box-shadow: inset 0 4px 15px rgba(0, 0, 0, 0.6);
            width: 100%;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            margin-bottom: 12px;
            overflow: hidden;
        }

        .items-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-template-rows: repeat(4, 1fr);
            gap: 8px;
            height: 100%;
            width: 100%;
            place-items: center;
        }

        /* LA TARJETA SE AJUSTA AL TAMAÑO NATURAL DE LA IMAGEN */
        .item-card {
            background: var(--adra-white);
            border-radius: 8px;
            padding: 0;
            display: inline-flex;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            position: relative;
            overflow: hidden;
            /* BORDE CAMUFLADO CON EL FONDO DE LA MÁQUINA */
            border: 2px solid var(--machine-inner-red);
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
        }

        .item-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.25), 0 4px 8px rgba(0, 0, 0, 0.15);
            z-index: 10;
            /* Borde se mantiene camuflado en hover */
            border-color: var(--machine-inner-red);
        }

        .item-card.active {
            transform: translateY(-5px);
            box-shadow: 0 12px 25px rgba(213, 0, 50, 0.4), 0 0 0 2px var(--adra-red), 0 6px 12px rgba(0, 0, 0, 0.2);
            z-index: 20;
            /* Borde rojo brillante solo el contorno interior */
            border-color: var(--machine-inner-red);
        }

        /* LA IMAGEN DEFINE EL TAMAÑO DE LA TARJETA */
        .item-image {
            display: block;
            background: var(--adra-white);
            border-radius: 6px;
            margin: 0;
            overflow: hidden;
            position: relative;
            border: none;
            padding: 0;
            line-height: 0;
        }

        .item-image img {
            display: block;
            width: 100%;
            height: auto;
            max-width: 100%;
            max-height: 100%;
        }

        .item-image i {
            font-size: 2rem;
            color: var(--adra-red);
        }

        .item-content {
            display: none;
        }

        .dispenser-area {
            height: 120px;
            background: linear-gradient(180deg, #000000 0%, #1a1a1a 100%);
            border-radius: 8px 8px 0 0;
            position: relative;
            overflow: hidden;
            box-shadow: inset 0 8px 16px rgba(0, 0, 0, 0.9), 0 -5px 15px rgba(0, 0, 0, 0.5);
            border: 3px solid #333;
            border-bottom: none;
        }

        .dispenser-light {
            position: absolute;
            top: 15px;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 10px;
            background: var(--adra-red);
            border-radius: 5px;
            box-shadow: 0 0 20px rgba(213, 0, 50, 0.8);
            opacity: 0.3;
            z-index: 4;
            animation: lightPulse 2s infinite;
        }

        @keyframes lightPulse {
            0%, 100% { opacity: 0.3; box-shadow: 0 0 20px rgba(213, 0, 50, 0.8); }
            50% { opacity: 1; box-shadow: 0 0 30px rgba(213, 0, 50, 1); }
        }

        .dispenser-light.active {
            animation: lightActive 0.5s 3;
        }

        @keyframes lightActive {
            0%, 100% { opacity: 0.3; box-shadow: 0 0 20px rgba(213, 0, 50, 0.8); }
            50% { opacity: 1; box-shadow: 0 0 40px rgba(213, 0, 50, 1); }
        }

        /* SHUTTER DE METAL - COLOR METÁLICO REALISTA */
        .shutter {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                /* Base de metal plateado/gris oscuro */
                linear-gradient(145deg, 
                    #4a4a4a 0%, 
                    #2a2a2a 25%, 
                    #3a3a3a 50%, 
                    #1a1a1a 75%, 
                    #4a4a4a 100%);
            border-radius: 8px 8px 0 0;
            border: 3px solid #555;
            border-bottom: 3px solid #333;
            z-index: 2;
            overflow: hidden;
            box-shadow: 
                /* Sombra interior para profundidad */
                inset 0 5px 15px rgba(0, 0, 0, 0.7),
                inset 0 -5px 15px rgba(255, 255, 255, 0.1),
                /* Brillo exterior metálico */
                0 0 10px rgba(100, 100, 100, 0.5),
                0 0 20px rgba(0, 0, 0, 0.3);
            
            /* Textura de franjas metálicas */
            background-image: 
                /* Líneas horizontales sutiles (relieve) */
                repeating-linear-gradient(
                    0deg,
                    transparent,
                    transparent 2px,
                    rgba(255, 255, 255, 0.05) 2px,
                    rgba(255, 255, 255, 0.05) 3px
                ),
                /* Líneas verticales (brillos metálicos) */
                repeating-linear-gradient(
                    90deg,
                    rgba(255, 255, 255, 0.1),
                    rgba(255, 255, 255, 0.1) 1px,
                    transparent 1px,
                    transparent 5px
                ),
                /* Puntos de textura metálica */
                radial-gradient(
                    circle at 25% 25%,
                    rgba(255, 255, 255, 0.05) 1px,
                    transparent 1px
                ),
                radial-gradient(
                    circle at 75% 75%,
                    rgba(0, 0, 0, 0.1) 1px,
                    transparent 1px
                );
            background-size: 
                100% 100%,
                20px 100%,
                10px 10px,
                10px 10px;
        }

        /* Borde brillante en la parte superior */
        .shutter::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, 
                rgba(150, 150, 150, 0.8) 0%,
                rgba(200, 200, 200, 0.9) 20%,
                rgba(255, 255, 255, 1) 50%,
                rgba(200, 200, 200, 0.9) 80%,
                rgba(150, 150, 150, 0.8) 100%);
            z-index: 3;
            box-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
        }

        /* ANIMACIÓN DE PERSIANA METÁLICA - LENTA Y POR FRANJAS */
        .shutter.open {
            animation: shutterRollDown 1.5s ease-out forwards;
        }

        @keyframes shutterRollDown {
            0% {
                height: 100%;
                opacity: 1;
            }
            10% {
                height: 90%;
                opacity: 0.95;
            }
            20% {
                height: 80%;
                opacity: 0.9;
            }
            30% {
                height: 70%;
                opacity: 0.85;
            }
            40% {
                height: 60%;
                opacity: 0.8;
            }
            50% {
                height: 50%;
                opacity: 0.75;
            }
            60% {
                height: 40%;
                opacity: 0.7;
            }
            70% {
                height: 30%;
                opacity: 0.65;
            }
            80% {
                height: 20%;
                opacity: 0.6;
            }
            90% {
                height: 10%;
                opacity: 0.55;
            }
            100% {
                height: 0%;
                opacity: 0;
                border-bottom: none;
            }
        }

        .dispenser-internal {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1;
            opacity: 0;
            transition: opacity 0.5s ease 0.4s;
            background: #000000;
            border-radius: 5px 5px 0 0;
        }

        .shutter.open ~ .dispenser-internal {
            opacity: 1;
        }

        @keyframes fallToDispenser {
            0% { 
                transform: translate(0, 0) scale(1); 
                opacity: 1; 
            }
            100% { 
                transform: translate(var(--end-x), var(--end-y)) scale(0.5); 
                opacity: 0;
            }
        }

        .falling-item {
            position: fixed;
            z-index: 1000;
            pointer-events: none;
            animation: fallToDispenser 0.8s ease-in forwards;
            /* Borde camuflado en tarjetas que caen */
            border: 2px solid var(--machine-inner-red) !important;
            border-radius: 8px !important;
            background: var(--adra-white) !important;
            overflow: hidden !important;
        }

        .falling-item .item-image {
            width: 100% !important;
            height: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            border-radius: 6px !important;
            overflow: hidden !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .falling-item .item-image img {
            width: 100% !important;
            height: 100% !important;
            object-fit: contain !important;
            display: block !important;
        }

        @media (min-width: 768px) {
            .falling-item {
                /* Borde más grueso en PC pero manteniendo el color camuflado */
                border-width: 3px !important;
                border-radius: 10px !important;
            }
            
            .falling-item .item-image {
                border-radius: 8px !important;
            }
            
            /* Shutter más detallado en PC */
            .shutter {
                background: 
                    linear-gradient(145deg, 
                        #5a5a5a 0%, 
                        #3a3a3a 25%, 
                        #4a4a4a 50%, 
                        #2a2a2a 75%, 
                        #5a5a5a 100%);
                box-shadow: 
                    inset 0 5px 20px rgba(0, 0, 0, 0.8),
                    inset 0 -5px 20px rgba(255, 255, 255, 0.15),
                    0 0 15px rgba(120, 120, 120, 0.6),
                    0 0 25px rgba(0, 0, 0, 0.4);
                background-image: 
                    repeating-linear-gradient(
                        0deg,
                        transparent,
                        transparent 3px,
                        rgba(255, 255, 255, 0.07) 3px,
                        rgba(255, 255, 255, 0.07) 4px
                    ),
                    repeating-linear-gradient(
                        90deg,
                        rgba(255, 255, 255, 0.12),
                        rgba(255, 255, 255, 0.12) 1px,
                        transparent 1px,
                        transparent 6px
                    ),
                    radial-gradient(
                        circle at 25% 25%,
                        rgba(255, 255, 255, 0.08) 1px,
                        transparent 1px
                    ),
                    radial-gradient(
                        circle at 75% 75%,
                        rgba(0, 0, 0, 0.15) 1px,
                        transparent 1px
                    );
                background-size: 
                    100% 100%,
                    25px 100%,
                    12px 12px,
                    12px 12px;
            }
            
            .shutter::before {
                height: 4px;
                box-shadow: 0 0 8px rgba(255, 255, 255, 0.7);
            }
            
            /* Animación más lenta en PC */
            .shutter.open {
                animation: shutterRollDown 2s ease-out forwards;
            }
        }

        /* TARJETA DISPENSADA - MISMA LÓGICA */
        .dispensed-card-container {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 130px;
            height: auto;
            z-index: 100;
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .dispensed-card {
            background: transparent;
            border-radius: 10px;
            padding: 0;
            display: inline-flex;
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.6);
            /* Borde camuflado en tarjeta dispensada */
            border: 3px solid var(--machine-inner-red);
            transform: scale(0);
            opacity: 0;
            animation: cardAppear 0.8s ease-out 0.5s forwards;
            overflow: hidden;
            position: relative;
            max-width: 100%;
            max-height: 100%;
        }

        @keyframes cardAppear {
            0% { transform: scale(0); opacity: 0; }
            70% { transform: scale(1.05); opacity: 1; }
            100% { transform: scale(1); opacity: 1; }
        }

        .dispensed-card .item-image {
            width: 100%;
            height: auto;
            margin: 0;
            padding: 0;
            border: none;
            border-radius: 0;
            background: none;
            position: relative;
        }

        .dispensed-card .item-image img {
            width: 100%;
            height: auto;
            display: block;
        }

        .dispensed-card .item-image i {
            font-size: 3rem;
        }

        .confirmation-modal .modal-content {
            background: var(--adra-white);
            border-radius: 12px;
            /* Borde del modal diferente (no necesita camuflarse) */
            border: 2px solid var(--adra-deep-red);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            color: var(--adra-red);
        }

        .confirmation-modal .modal-header {
            /* Borde inferior diferente */
            border-bottom: 2px solid var(--adra-deep-red);
            background: var(--adra-white);
        }

        .confirmation-modal .modal-header .modal-title {
            color: var(--adra-red);
            font-weight: 700;
            width: 100%;
            text-align: center;
        }

        .confirmation-modal .modal-body {
            padding: 1.5rem;
            text-align: center;
            background: var(--adra-white);
        }

        .confirmation-modal .modal-footer {
            /* Borde superior diferente */
            border-top: 2px solid var(--adra-deep-red);
            background: var(--adra-white);
            display: flex;
            justify-content: center;
            gap: 1rem;
        }

        .confirmation-image-container {
            width: 100%;
            display: flex;
            justify-content: center;
            margin-bottom: 1rem;
        }

        .confirmation-image {
            width: 100px;
            height: auto;
            background: linear-gradient(135deg, var(--adra-cream), var(--adra-pale-blue));
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            /* Borde diferente en la imagen de confirmación */
            border: 2px solid var(--adra-deep-red);
        }

        .confirmation-image img {
            width: 100%;
            height: auto;
            display: block;
        }

        .confirmation-image i {
            font-size: 2.5rem;
            color: var(--adra-red);
        }

        .confirmation-item-name {
            font-size: 1.3rem;
            font-weight: 800;
            color: var(--adra-red);
            margin-bottom: 0.5rem;
        }

        .confirmation-item-desc {
            font-size: 1rem;
            color: var(--text-medium);
            line-height: 1.4;
            margin-bottom: 0;
        }

        .confirmation-cancel-btn {
            background: #6c757d;
            border-color: #6c757d;
            color: var(--adra-white);
            font-weight: 600;
            padding: 0.4rem 1.2rem;
        }

        .confirmation-donate-btn {
            background: var(--adra-red);
            border-color: var(--adra-red);
            color: var(--adra-white);
            font-weight: 600;
            padding: 0.4rem 1.2rem;
        }

        .confirmation-cancel-btn:hover {
            background: #5a6268;
            border-color: #545b62;
        }

        .confirmation-donate-btn:hover {
            background: var(--adra-deep-red);
            border-color: var(--adra-deep-red);
        }

        /* RESPONSIVO PARA PC - MANTENER DIMENSIÓN VERTICAL */
        @media (min-width: 768px) {
            body {
                padding: 20px;
            }
            
            /* MANTENER EL MÁXIMO ANCHO EN 500px PARA PC TAMBIÉN */
            .vending-container {
                max-width: 500px; /* MANTENEMOS EL MISMO ANCHO QUE EN MÓVIL */
                max-height: 90vh;
                height: 90vh;
                border-radius: 20px;
                padding: 20px;
                /* Centrar horizontalmente en pantallas grandes */
                margin: 0 auto;
            }
            
            /* MEJORAR EL ESPACIADO INTERNO */
            .items-grid {
                gap: 12px;
            }
            
            .item-card {
                border-radius: 10px;
                /* Borde más grueso en PC pero manteniendo el color camuflado */
                border-width: 3px;
            }
            
            /* Aumentar un poco el tamaño de la tarjeta dispensada */
            .dispensed-card-container {
                width: 150px;
                top: 20px;
                right: 20px;
            }
            
            .dispenser-area {
                height: 140px;
                border-radius: 10px 10px 0 0;
            }
            
            .dispenser-light {
                width: 80px;
                height: 12px;
                top: 20px;
            }
            
            .confirmation-image {
                width: 120px;
            }
            
            .confirmation-item-name {
                font-size: 1.5rem;
            }
            
            .confirmation-item-desc {
                font-size: 1.1rem;
            }
        }

        /* Para pantallas muy grandes pero mantener verticalidad */
        @media (min-width: 1200px) {
            .vending-container {
                max-width: 550px; /* Solo un poco más grande, pero manteniendo vertical */
                max-height: 85vh;
            }
            
            .items-grid {
                gap: 15px;
            }
            
            .dispensed-card-container {
                width: 160px;
            }
        }

        /* RESPONSIVO PARA MÓVIL */
        @media (max-width: 767px) {
            body {
                padding: 8px;
            }
            
            .vending-container {
                max-width: 100%;
                height: 100vh;
                max-height: 100vh;
                border-radius: 0;
                padding: 8px;
            }
            
            .items-grid {
                gap: 6px;
            }
            
            .item-card {
                border-radius: 6px;
                border-width: 2px;
            }
            
            .dispenser-area {
                height: 100px;
            }
            
            .dispensed-card-container {
                width: 100px;
                top: 10px;
                right: 10px;
            }
            
            .confirmation-image {
                width: 80px;
            }
            
            .confirmation-item-name {
                font-size: 1.1rem;
            }
            
            .confirmation-item-desc {
                font-size: 0.9rem;
            }
        }

        /* Para pantallas horizontales (landscape) en móvil */
        @media (max-height: 600px) and (orientation: landscape) {
            .vending-container {
                max-height: 100vh;
                padding: 6px;
                /* En landscape móvil, mantener el ancho pero ajustar altura */
                max-width: 100%;
                width: 100%;
            }
            
            .items-grid {
                gap: 4px;
            }
            
            .dispenser-area {
                height: 80px;
            }
            
            .dispensed-card-container {
                width: 90px;
                top: 8px;
                right: 8px;
            }
        }

        /* Para PC en modo horizontal - prevenir que se estire */
        @media (min-width: 768px) and (orientation: landscape) {
            .vending-container {
                /* Mantener el mismo ancho máximo que en portrait */
                max-width: 500px;
                /* Permitir que sea un poco más alto si hay espacio */
                max-height: 95vh;
            }
        }

        /* Estilos específicos para modo claro en móvil */
        @media (prefers-color-scheme: light) {
            html, body {
                background-color: #000000 !important;
            }
        }
    </style>
</head>
<body>
    <div class="vending-container">
        <div class="items-display">
            <div class="items-grid" id="itemsGrid"></div>
        </div>

        <div class="dispensed-card-container" id="dispensedCardContainer"></div>

        <div class="dispenser-area">
            <div class="dispenser-light" id="dispenserLight"></div>
            <div class="shutter" id="shutter"></div>
            <div class="dispenser-internal" id="dispenserInternal"></div>
        </div>
    </div>

    <div class="modal fade confirmation-modal" id="confirmationModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Confirmar Donación</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="confirmation-image-container">
                        <div class="confirmation-image" id="confirmationImage"></div>
                    </div>
                    <h4 id="confirmationItemName" class="confirmation-item-name"></h4>
                    <p class="confirmation-item-desc" id="confirmationItemDesc"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn confirmation-cancel-btn" data-bs-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn confirmation-donate-btn" id="confirmDonationBtn">Sí, Donar</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Precargar la imagen de fondo para evitar parpadeos
            const bgImage = new Image();
            bgImage.src = 'fondo-navidad.jpeg';
            
            // Forzar modo oscuro en la página
            if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
                document.documentElement.style.backgroundColor = '#000000';
                document.body.style.backgroundColor = '#000000';
            }

            const itemsGrid = document.getElementById('itemsGrid');
            const shutter = document.getElementById('shutter');
            const dispenserInternal = document.getElementById('dispenserInternal');
            const dispenserLight = document.getElementById('dispenserLight');
            const dispensedCardContainer = document.getElementById('dispensedCardContainer');
            const confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));
            const confirmationImage = document.getElementById('confirmationImage');
            const confirmationItemName = document.getElementById('confirmationItemName');
            const confirmationItemDesc = document.getElementById('confirmationItemDesc');
            const confirmDonationBtn = document.getElementById('confirmDonationBtn');

            // Crear elementos de audio
            const clickSound = new Audio('sounds/click.mp3');
            const appearSound = new Audio('sounds/appear.mp3');
            const shutterSound = new Audio('sounds/shutter.mp3');

            let selectedItemId = null;
            let selectedItemPrecio = null;
            let selectedItemData = null;
            let currentFallingItem = null;

            const items = [
                { id: 1, name: "Frazadas", precio: 10.00, imagen: "img/1.png" },
                { id: 2, name: "Refugio", precio: 15.00, imagen: "img/2.png" },
                { id: 3, name: "Kit de higiene", precio: 10.00, imagen: "img/3.png" },
                { id: 4, name: "Mochila", precio: 15.00, imagen: "img/4.png" },
                { id: 5, name: "Libros y juegos", precio: 15.00, imagen: "img/5.png" },
                { id: 6, name: "Barra energética", precio: 10.00, imagen: "img/6.png" },
                { id: 7, name: "Taller", precio: 15.00, imagen: "img/7.png" },
                { id: 8, name: "Combustible", precio: 10.00, imagen: "img/8.png" },
                { id: 9, name: "Jabas", precio: 10.00, imagen: "img/9.png" },
                { id: 10, name: "Alimento Caliente", precio: 10.00, imagen: "img/10.png" },
                { id: 11, name: "Alimentos", precio: 30.00, imagen: "img/11.png" },
                { id: 12, name: "Abrigo", precio: 40.00, imagen: "img/12.png" },
                { id: 13, name: "Calzados", precio: 50.00, imagen: "img/13.png" },
                { id: 14, name: "Kit Solar", precio: 40.00, imagen: "img/14.png" },
                { id: 15, name: "Baño Digno", precio: 100.00, imagen: "img/15.png" },
                { id: 16, name: "Casa Abrigadora", precio: 100.00, imagen: "img/16.png" }
            ];

            function generateItems() {
                itemsGrid.innerHTML = '';
                for (let i = 0; i < 16; i++) {
                    const item = items[i % items.length];
                    const itemCard = document.createElement('div');
                    itemCard.className = 'item-card';
                    itemCard.dataset.id = item.id;
                    itemCard.dataset.name = item.name;
                    itemCard.dataset.precio = item.precio;
                    itemCard.dataset.imagen = item.imagen;
                    
                    itemCard.innerHTML = `
                        <div class="item-image">
                            <img src="${item.imagen}" alt="${item.name}" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                            <i class="bi bi-gift" style="display:none;"></i>
                        </div>
                    `;
                    
                    itemsGrid.appendChild(itemCard);
                    
                    // Precargar imagen para evitar saltos
                    const img = new Image();
                    img.src = item.imagen;
                }
            }

            generateItems();

            itemsGrid.addEventListener('click', function(e) {
                const card = e.target.closest('.item-card');
                if (card) {
                    // Reproducir sonido de clic
                    clickSound.currentTime = 0;
                    clickSound.play();
                    
                    document.querySelectorAll('.item-card').forEach(c => c.classList.remove('active'));
                    card.classList.add('active');
                    
                    selectedItemId = card.dataset.id;
                    selectedItemPrecio = card.dataset.precio;
                    selectedItemData = {
                        name: card.dataset.name,
                        precio: card.dataset.precio,
                        imagen: card.dataset.imagen
                    };
                    
                    cleanPreviousAnimations();
                    startDispensingSequence(card);
                }
            });

            confirmDonationBtn.addEventListener('click', function() {
                if (selectedItemId && selectedItemPrecio) {
                    // Reproducir sonido de shutter antes de redirigir
                    shutterSound.currentTime = 0;
                    shutterSound.play();
                    
                    // Esperar a que termine el sonido antes de redirigir
                    setTimeout(() => {
                        dispensedCardContainer.style.display = 'none';
                        dispensedCardContainer.innerHTML = '';
                        confirmationModal.hide();
                        
                        setTimeout(() => {
                            window.location.href = `formulario_donacion.php?item_id=${selectedItemId}&precio=${selectedItemPrecio}`;
                        }, 300);
                    }, 500); // Tiempo suficiente para que se escuche el sonido
                }
            });

            function cleanPreviousAnimations() {
                if (currentFallingItem) {
                    document.body.removeChild(currentFallingItem);
                    currentFallingItem = null;
                }
                shutter.classList.remove('open');
                shutter.style.animation = 'none';
                // Forzar reflow para reiniciar animación
                void shutter.offsetWidth;
                shutter.style.animation = '';
                dispenserLight.classList.remove('active');
                dispenserInternal.innerHTML = '';
            }

            function startDispensingSequence(card) {
                createFallingItem(card);
                
                setTimeout(() => {
                    dispenserLight.classList.add('active');
                    shutter.classList.add('open');
                    
                    // Reproducir sonido appear cuando empiece la animación de la cortina
                    appearSound.currentTime = 0;
                    appearSound.play();
                    
                    createCardInDispenser(card);
                }, 800);
                
                // Tiempo ajustado para la animación más lenta
                setTimeout(() => {
                    shutter.classList.remove('open');
                    dispenserLight.classList.remove('active');
                    setTimeout(() => {
                        dispenserInternal.innerHTML = '';
                    }, 300);
                }, 2800); // 800ms caída + 2000ms animación shutter
                
                setTimeout(() => {
                    showDispensedCard(card);
                    setTimeout(() => {
                        showConfirmationModal(selectedItemData);
                    }, 500);
                }, 3100); // 2800ms + 300ms
            }

            function createFallingItem(card) {
                const rect = card.getBoundingClientRect();
                const dispenserRect = document.querySelector('.dispenser-area').getBoundingClientRect();
                
                const endX = dispenserRect.left + (dispenserRect.width / 2) - (rect.width / 2);
                const endY = dispenserRect.top + (dispenserRect.height / 2) - (rect.height / 2);
                
                // Clonar SOLO la estructura necesaria
                const fallingItem = document.createElement('div');
                fallingItem.className = 'item-card falling-item';
                
                // Copiar todos los atributos de datos
                fallingItem.dataset.id = card.dataset.id;
                fallingItem.dataset.name = card.dataset.name;
                fallingItem.dataset.precio = card.dataset.precio;
                fallingItem.dataset.imagen = card.dataset.imagen;
                
                // Crear la misma estructura HTML que la tarjeta original
                fallingItem.innerHTML = `
                    <div class="item-image">
                        <img src="${card.dataset.imagen}" alt="${card.dataset.name}" 
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                        <i class="bi bi-gift" style="display:none;"></i>
                    </div>
                `;
                
                // Aplicar estilos de posición y animación
                fallingItem.style.setProperty('--end-x', `${endX - rect.left}px`);
                fallingItem.style.setProperty('--end-y', `${endY - rect.top}px`);
                
                // Copiar las dimensiones exactas de la tarjeta original
                fallingItem.style.width = `${rect.width}px`;
                fallingItem.style.height = `${rect.height}px`;
                fallingItem.style.left = `${rect.left}px`;
                fallingItem.style.top = `${rect.top}px`;
                
                // Estilos fijos para la animación
                fallingItem.style.position = 'fixed';
                fallingItem.style.zIndex = '1000';
                fallingItem.style.pointerEvents = 'none';
                fallingItem.style.boxSizing = 'border-box';
                
                // Asegurar que la imagen mantenga las proporciones
                const img = fallingItem.querySelector('img');
                if (img) {
                    img.style.width = '100%';
                    img.style.height = '100%';
                    img.style.objectFit = 'contain';
                    img.style.display = 'block';
                }
                
                // Asegurar que el contenedor de la imagen ocupe todo el espacio
                const imageContainer = fallingItem.querySelector('.item-image');
                if (imageContainer) {
                    imageContainer.style.width = '100%';
                    imageContainer.style.height = '100%';
                    imageContainer.style.margin = '0';
                    imageContainer.style.padding = '0';
                }
                
                document.body.appendChild(fallingItem);
                currentFallingItem = fallingItem;
                
                setTimeout(() => {
                    if (currentFallingItem && currentFallingItem.parentNode) {
                        document.body.removeChild(currentFallingItem);
                        currentFallingItem = null;
                    }
                }, 800);
            }

            function createCardInDispenser(card) {
                dispenserInternal.innerHTML = '';
                
                // Crear una tarjeta especial para el dispensador con dimensiones fijas
                const dispenserCard = document.createElement('div');
                dispenserCard.style.width = '140px';
                dispenserCard.style.height = '170px';
                dispenserCard.style.opacity = '1';
                dispenserCard.style.transform = 'scale(0.5)';
                dispenserCard.style.boxShadow = '0 0 30px rgba(255, 255, 255, 0.6)';
                /* Borde camuflado en tarjeta dentro del dispensador */
                dispenserCard.style.border = '2px solid var(--machine-inner-red)';
                dispenserCard.style.borderRadius = '8px';
                dispenserCard.style.overflow = 'hidden';
                dispenserCard.style.display = 'flex';
                dispenserCard.style.alignItems = 'center';
                dispenserCard.style.justifyContent = 'center';
                dispenserCard.style.background = 'var(--adra-white)';
                dispenserCard.style.position = 'relative';
                
                // Crear el contenedor de la imagen
                const imageContainer = document.createElement('div');
                imageContainer.style.width = '100%';
                imageContainer.style.height = '100%';
                imageContainer.style.display = 'flex';
                imageContainer.style.alignItems = 'center';
                imageContainer.style.justifyContent = 'center';
                imageContainer.style.overflow = 'hidden';
                
                // Crear la imagen
                const img = document.createElement('img');
                img.src = card.dataset.imagen;
                img.alt = card.dataset.name;
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'contain';
                img.style.display = 'block';
                
                // Manejar error de la imagen
                img.onerror = function() {
                    this.style.display = 'none';
                    const icon = document.createElement('i');
                    icon.className = 'bi bi-gift';
                    icon.style.fontSize = '3rem';
                    icon.style.color = 'var(--adra-red)';
                    imageContainer.appendChild(icon);
                };
                
                imageContainer.appendChild(img);
                dispenserCard.appendChild(imageContainer);
                dispenserInternal.appendChild(dispenserCard);
            }

            function showDispensedCard(card) {
                dispensedCardContainer.innerHTML = '';
                
                const dispensedCard = document.createElement('div');
                dispensedCard.className = 'dispensed-card';
                
                
                dispensedCardContainer.appendChild(dispensedCard);
                dispensedCardContainer.style.display = 'flex';
            }

            function showConfirmationModal(itemData) {
                const nombre = itemData.name;
                const precio = itemData.precio;
                const imagen = itemData.imagen;
                
                confirmationItemName.textContent = nombre;
                confirmationItemDesc.textContent = `Precio: S/ ${parseFloat(precio).toFixed(2)}`;
                confirmationImage.innerHTML = '';
                
                if (imagen) {
                    const img = document.createElement('img');
                    img.src = imagen;
                    img.alt = nombre;
                    img.onerror = function() {
                        this.style.display = 'none';
                        const icon = document.createElement('i');
                        icon.className = 'bi bi-gift';
                        confirmationImage.appendChild(icon);
                    };
                    confirmationImage.appendChild(img);
                } else {
                    const icon = document.createElement('i');
                    icon.className = 'bi bi-gift';
                    confirmationImage.appendChild(icon);
                }
                
                confirmationModal.show();
            }
            
            document.getElementById('confirmationModal').addEventListener('hidden.bs.modal', function() {
                dispensedCardContainer.style.display = 'none';
                dispensedCardContainer.innerHTML = '';
                selectedItemId = null;
                selectedItemPrecio = null;
                selectedItemData = null;
                document.querySelectorAll('.item-card').forEach(c => c.classList.remove('active'));
            });
        });
    </script>
</body>
</html>