<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Textiles May - Pijamas Modernas con Estampados</title>
    <link rel="icon" type="image/png" href="https://textilesmay.shop/wp-content/uploads/2025/03/cropped-cropped-log-1.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Poppins:wght@600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            scroll-behavior: smooth;
            background-color: #FFD1DC;
            background-repeat: no-repeat;
            background-position: center top;
            background-size: cover;
            background-attachment: fixed;
        }
        h1, h2, h3, h4 { font-family: 'Poppins', sans-serif; }
        .bg-primary-pink { background-color: #FFD1DC; }
        .text-accent-pink { color: #D1306C; }
        .btn-primary { background-color: #D1306C; color: white; transition: background-color 0.3s ease; padding: 0.5rem 1rem; border-radius: 0.375rem; /* rounded-md */ }
        .btn-primary:hover { background-color: #B72A5D; }
        .btn-secondary { background-color: #4A5568; color: white; transition: background-color 0.3s ease; padding: 0.5rem 1rem; border-radius: 0.375rem; /* rounded-md */ }
        .btn-secondary:hover { background-color: #2D3748; }
        .btn-danger { background-color: #E53E3E; color: white; transition: background-color 0.3s ease; padding: 0.5rem 1rem; border-radius: 0.375rem; }
        .btn-danger:hover { background-color: #C53030; }
        .btn-info { background-color: #3182CE; color: white; transition: background-color 0.3s ease; padding: 0.5rem 1rem; border-radius: 0.375rem; }
        .btn-info:hover { background-color: #2B6CB0; }

        /* Estilos para la cabecera fija */
        #hero-header-section {
            min-height: 45vh;
            height: 60vh;
            max-height: 800px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            background-color: #FFD1DC;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
        .hero-header-overlay {
            background-color: rgba(209, 48, 108, 0.4);
            position: absolute;
            inset: 0;
        }

        @keyframes bounce-in {
            0% { transform: scale(0.5); opacity: 0; }
            70% { transform: scale(1.1); opacity: 1; }
            100% { transform: scale(1); }
        }
        .btn-animate { animation: bounce-in 0.8s ease-out; }

        @keyframes text-pulse {
            0% { color: #D1306C; transform: scale(1); }
            50% { color: #FF69B4; transform: scale(1.02); }
            100% { color: #D1306C; transform: scale(1); }
        }
        .animate-text-pulse { animation: text-pulse 2s infinite ease-in-out; }

        @keyframes badge-pop {
            0% { transform: scale(1); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }
        .cart-count-badge-animated { animation: badge-pop 0.3s ease-out; }

        #cart-count-badge {
            top: 0.25rem; right: 0.25rem; transform: translate(0, 0);
            min-width: 1.5rem; height: 1.5rem; line-height: 1.5rem; font-size: 0.75rem;
        }

        .section-bg-short { background-image: url('https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.01-AM-1.jpeg'); }
        .section-bg-capri { background-image: url('https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.00-PM-1.jpeg'); }
        .section-bg-pantalon { background-image: url('https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.36-PM-1.jpeg'); }
        .section-bg-ninas { background-image: url('https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.52.18-PM-1.jpeg'); }
        .section-bg-short, .section-bg-capri, .section-bg-pantalon, .section-bg-ninas {
            background-size: cover; background-position: center;
            position: relative;
            z-index: 0;
        }

        .section-overlay {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background-color: rgba(255, 255, 255, 0.7); z-index: -1;
        }
        .section-content { position: relative; z-index: 1; }

        /* Admin Modal Styles */
        .admin-modal-input {
            @apply w-full p-2 border border-pink-300 rounded-md focus:outline-none focus:ring-2 focus:ring-accent-pink;
        }
        .admin-modal-label {
            @apply block text-sm font-medium text-slate-700 mb-1;
        }
        .admin-product-card {
            @apply bg-pink-50 p-4 rounded-lg shadow mb-4 border border-pink-200;
        }
        .admin-talla-item {
            @apply flex items-center space-x-2 mb-2;
        }
        #admin-add-new-product-form {
            @apply bg-pink-100 p-4 rounded-lg shadow mt-6 border border-accent-pink;
        }

        /* Responsive adjustments for header section */
        @media (max-width: 768px) {
            #hero-header-section {
                height: 50vh;
            }
            #hero-header-section h2 {
                font-size: 3rem;
            }
        }

        /* Animation for the "Emprende y Gana" section */
        @keyframes pulse-border {
            0% { box-shadow: 0 0 0 0 rgba(209, 48, 108, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(209, 48, 108, 0); }
            100% { box-shadow: 0 0 0 0 rgba(209, 48, 108, 0); }
        }
        .animate-pulse-border {
            animation: pulse-border 2s infinite;
        }

        /* Styles for the floating "Oferta" button */
        #offer-button {
            position: fixed;
            top: 50%;
            left: 1rem;
            transform: translateY(-50%);
            z-index: 90;
            background-color: #D1306C;
            color: white;
            padding: 1rem 2rem;
            border-radius: 9999px;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        }
        #offer-button:hover {
            background-color: #B72A5D;
            transform: translateY(-50%) scale(1.05);
        }

        /* Animation for the floating "Oferta" button */
        @keyframes offer-button-pulse {
            0% { transform: translateY(-50%) scale(1); box-shadow: 0 0 0 0 rgba(209, 48, 108, 0.7); }
            70% { transform: translateY(-50%) scale(1.05); box-shadow: 0 0 0 15px rgba(209, 48, 108, 0); }
            100% { transform: translateY(-50%) scale(1); box-shadow: 0 0 0 0 rgba(209, 48, 108, 0); }
        }
        .offer-button-animated {
            animation: offer-button-pulse 2s infinite;
        }

        /* Styles for the offer modal */
        #offer-modal {
            position: fixed;
            inset: 0;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 200;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        #offer-modal.show {
            opacity: 1;
            visibility: visible;
        }
        #offer-modal-content {
            background-color: white;
            padding: 1rem;
            border-radius: 1rem;
            box-shadow: 0 8px 25px rgba(0,0,0,0.4);
            position: relative;
            max-width: 90%;
            max-height: 90%;
            overflow: hidden;
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }
        #offer-modal.show #offer-modal-content {
            transform: scale(1);
        }
        #offer-modal-image {
            width: 100%;
            height: auto;
            display: block;
            border-radius: 0.75rem;
        }
        #offer-modal-close-btn {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 50%;
            width: 2rem;
            height: 2rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: #D1306C;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.2s ease, color 0.2s ease;
        }
        #offer-modal-close-btn:hover {
            background-color: #D1306C;
            color: white;
        }

        /* Product Slider Container (horizontal scroll) */
        /* This is the container that holds the slider wrapper */
        .product-slider-container {
            overflow-x: auto; /* Enable horizontal scrolling */
            -webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */
            position: relative;
            padding-bottom: 1rem; /* Space for scrollbar */
        }
        /* Make scrollbar visible (default behavior after removing hiding rules) */

        .product-slider-wrapper {
            display: flex;
            flex-wrap: nowrap; /* Prevent items from wrapping */
            transition: transform 0.5s ease-in-out; /* Smooth transition for clicks */
        }
        .product-slider-item {
            flex-shrink: 0; /* Prevent items from shrinking */
            width: 100%; /* Default to full width on small screens */
            box-sizing: border-box;
            padding: 0.5rem; /* Consistent padding */
        }
        /* Adjust width for responsive display of items */
        @media (min-width: 640px) { /* sm breakpoint */
            .product-slider-item {
                width: calc(100% / 2); /* Show 2 items per row on sm+ */
            }
        }
        @media (min-width: 768px) { /* md breakpoint */
            .product-slider-item {
                width: calc(100% / 3); /* Show 3 items per row on md+ */
            }
        }

        /* New Slider Navigation Buttons for Product Sections */
        .slider-nav-btn {
            background-color: rgba(209, 48, 108, 0.7);
            color: white;
            padding: 0.5rem 0.75rem;
            border-radius: 9999px;
            transition: background-color 0.3s ease;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
            cursor: pointer;
            display: flex; /* Ensure buttons are visible */
            align-items: center;
            justify-content: center;
        }
        .slider-nav-btn:hover {
            background-color: rgba(183, 42, 93, 0.9);
        }
        .slider-prev { left: 0.5rem; }
        .slider-next { right: 0.5rem; }


        @media (max-width: 640px) {
            #offer-button {
                padding: 0.75rem 1.5rem;
                font-size: 1.2rem;
                left: 0.5rem;
            }
            #offer-modal-content {
                padding: 0.5rem;
            }
            #offer-modal-image {
                border-radius: 0.5rem;
            }
            #offer-modal-close-btn {
                font-size: 1.2rem;
                width: 1.75rem;
                height: 1.75rem;
            }
        }

    </style>
</head>
<body class="text-slate-800">

    <header class="bg-white shadow-lg sticky top-0 z-50">
        <nav class="container mx-auto px-4 py-3 flex items-center">
            <a href="#" class="flex-shrink-0">
                <img src="https://textilesmay.shop/wp-content/uploads/2025/03/cropped-cropped-log-1.png" alt="Logo de Textiles May" onerror="this.onerror=null;this.src='https://placehold.co/100x64/FFD1DC/D1306C?text=Logo';" class="h-12 md:h-16">
            </a>
            <div class="hidden md:flex flex-grow justify-center space-x-6">
                <a href="#pijamas-short" class="text-slate-700 hover:text-accent-pink font-semibold transition-colors">Short</a>
                <a href="#pijamas-capri" class="text-slate-700 hover:text-accent-pink font-semibold transition-colors">Capri</a>
                <a href="#pijamas-pantalon" class="text-slate-700 hover:text-accent-pink font-semibold transition-colors">Pantalón</a>
                <a href="#pijamas-ninas" class="text-slate-700 hover:text-accent-pink font-semibold transition-colors">Niñas</a>
            </div>
            <button id="open-cart-modal" class="relative ml-auto bg-accent-pink text-white p-2 md:p-3 rounded-full shadow-lg hover:scale-110 transition-transform duration-200 z-40">
                <img src="https://textilesmay.shop/wp-content/uploads/2025/05/pngtree-ai-expansion-wind-e-commerce-element-pink-shopping-cart-vector-png-image_11338745.png" alt="Icono de Carrito de Compras" onerror="this.onerror=null;this.src='https://placehold.co/40x40/D1306C/FFFFFF?text=Cart';" class="w-8 h-8 md:w-10 md:h-10 object-contain">
                <span id="cart-count-badge" class="absolute inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white bg-red-600 rounded-full hidden">0</span>
            </button>
            <button id="mobile-menu-button" class="md:hidden text-slate-700 hover:text-accent-pink focus:outline-none ml-4">
                ☰
            </button>
        </nav>
        <div id="mobile-menu" class="hidden md:hidden bg-white py-2 shadow-md">
            <a href="#pijamas-short" class="block px-4 py-2 text-slate-700 hover:bg-pink-100">Short</a>
            <a href="#pijamas-capri" class="block px-4 py-2 text-slate-700 hover:bg-pink-100">Capri</a>
            <a href="#pijamas-pantalon" class="block px-4 py-2 text-slate-700 hover:bg-pink-100">Pantalón</a>
            <a href="#pijamas-ninas" class="block px-4 py-2 text-slate-700 hover:bg-pink-100">Niñas</a>
        </div>
    </header>

    <main class="pt-8" id="main-content-area">
        <!-- Static Header Section with a single image -->
        <section id="hero-header-section" class="relative flex items-center justify-center min-h-[45vh] h-[60vh] max-h-[800px] bg-cover bg-center bg-no-repeat" style="background-image: url('https://textilesmay.shop/wp-content/uploads/2025/06/33.png');">
            <div class="hero-header-overlay absolute inset-0"></div>
            <div class="relative z-10 flex flex-col items-center justify-center h-full text-center p-4">
                <h2 class="text-5xl md:text-7xl font-extrabold text-white leading-tight mb-6 drop-shadow-lg">
                    CATÁLOGO DE PIJAMAS
                </h2>
            </div>
        </section>

        <section id="emprende" class="py-20 px-4 md:px-6 bg-white text-center shadow-lg rounded-lg mx-auto max-w-4xl mt-12 animate-pulse-border">
            <h2 class="text-5xl font-extrabold text-accent-pink mb-6 leading-tight animate-text-pulse">
                Emprende y Gana
            </h2>
            <p class="text-xl md:text-2xl text-slate-700 mb-10 max-w-3xl mx-auto">
                ¿Sueñas con tu propio negocio? Únete a nuestra comunidad de promotoras y haz crecer tus ingresos
                comercializando las pijamas más modernas y cómodas del mercado. ¡Crece con nosotros!
            </p>
            <a href="https://chat.whatsapp.com/GQz4gT5upSZ04ZuREIr6cb" target="_blank" class="inline-block btn-primary text-xl font-bold px-12 py-5 rounded-full shadow-xl hover:scale-105 transform transition-transform duration-300 btn-animate">
                Únete a la Comunidad de Promotoras
            </a>
        </section>
        
        <div id="product-sections-container">
            <!-- Product sections will be dynamically inserted here by JavaScript -->
        </div>

    </main>

    <footer class="bg-slate-800 text-white py-10 px-4 md:px-6 mt-12">
        <div class="container mx-auto grid grid-cols-1 md:grid-cols-3 gap-8 text-center md:text-left">
            <div>
                <h4 class="text-xl font-bold mb-4 text-accent-pink">Textiles May</h4>
                <p class="text-sm">Especialistas en pijamas modernas para mujeres y niñas con estampados únicos.</p>
            </div>
            <div>
                <h4 class="text-xl font-bold mb-4 text-accent-pink">Contacto</h4>
                <p class="text-sm">Email: info@textilesmay.com</p>
                <p class="text-sm">Dirección: Carrera 106B # 60C - 81, Medellín, Colombia</p>
            </div>
            <div>
                <h4 class="text-xl font-bold mb-4 text-accent-pink">Síguenos</h4>
                <div class="flex justify-center md:justify-start space-x-4 text-2xl">
                    <a href="#" aria-label="Facebook" class="hover:text-accent-pink"><i class="fab fa-facebook-f"></i></a>
                    <a href="#" aria-label="Instagram" class="hover:text-accent-pink"><i class="fab fa-instagram"></i></a>
                </div>
                <p class="text-xs mt-4">&copy; 2025 Textiles May. Todos los derechos reservados.</p>
            </div>
        </div>
        <div class="text-center mt-8 border-t border-slate-700 pt-4">
            <button id="admin-login-btn" class="text-sm text-slate-400 hover:text-accent-pink">Acceso Admin</button>
        </div>
    </footer>

    <!-- Floating Offer Button -->
    <button id="offer-button" class="offer-button-animated">
        ¡Oferta!
    </button>

    <!-- Offer Modal -->
    <div id="offer-modal" class="hidden">
        <div id="offer-modal-content">
            <button id="offer-modal-close-btn">&times;</button>
            <img id="offer-modal-image" src="https://textilesmay.shop/wp-content/uploads/2025/06/SHORT1.png" alt="Oferta Especial Pijamas">
        </div>
    </div>

    <!-- Cart Modal -->
    <div id="cart-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100] hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 w-11/12 max-w-2xl max-h-[90vh] overflow-y-auto relative">
            <button id="close-cart-modal" class="absolute top-3 right-3 text-gray-500 hover:text-gray-800 text-3xl font-bold">&times;</button>
            <h3 class="text-3xl font-bold text-accent-pink mb-6 text-center">Tu Pedido</h3>
            <div id="cart-items-display" class="space-y-4 mb-8"></div>
            <div id="cart-empty-message" class="text-center text-slate-600 hidden">El carrito está vacío.</div>
            <div class="space-y-4 mt-6">
                <input type="text" id="customer-name" placeholder="Nombre completo" class="w-full p-3 border border-pink-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-accent-pink shadow-sm">
                <input type="text" id="customer-address" placeholder="Dirección de envío" class="w-full p-3 border border-pink-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-accent-pink shadow-sm">
                <input type="text" id="customer-city" placeholder="Ciudad" class="w-full p-3 border border-pink-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-accent-pink shadow-sm">
                <input type="email" id="customer-email" placeholder="Correo electrónico (opcional)" class="w-full p-3 border border-pink-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-accent-pink shadow-sm">
            </div>
            <div class="flex flex-col md:flex-row justify-center space-y-4 md:space-y-0 md:space-x-4 mt-8">
                <button id="print-order-btn" class="btn-primary px-8 py-3 rounded-lg text-lg font-semibold shadow-md hover:shadow-lg">Descargar/Imprimir Pedido</button>
                <button id="whatsapp-order-btn" class="bg-green-500 text-white px-8 py-3 rounded-lg text-lg font-semibold shadow-md hover:bg-green-600 hover:shadow-lg flex items-center justify-center space-x-2">
                    <i class="fab fa-whatsapp"></i>
                    <span>Enviar por WhatsApp</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Custom Alert Modal -->
    <div id="custom-alert-modal" class="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-[200] hidden transition-opacity duration-300 opacity-0">
        <div class="bg-white p-6 rounded-xl shadow-2xl w-11/12 max-w-md text-center transform scale-95 transition-transform duration-300">
            <h4 id="custom-alert-title" class="text-2xl font-bold text-accent-pink mb-4">Alerta</h4>
            <p id="custom-alert-message" class="text-slate-700 mb-6">Este es un mensaje de alerta.</p>
            <div id="custom-alert-buttons" class="flex justify-center space-x-3">
                <button id="custom-alert-close-btn" class="btn-primary px-6 py-2 rounded-lg font-semibold">Entendido</button>
                <!-- Confirm/Cancel buttons will be added here by JS if needed -->
            </div>
        </div>
    </div>

    <!-- Admin Login Modal -->
    <div id="admin-login-modal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-[150] hidden">
        <div class="bg-white p-8 rounded-lg shadow-xl w-11/12 max-w-md">
            <h3 class="text-2xl font-bold text-accent-pink mb-6 text-center">Acceso Administrativo</h3>
            <div class="space-y-4">
                <div>
                    <label for="admin-username" class="admin-modal-label">Usuario:</label>
                    <input type="text" id="admin-username" class="admin-modal-input">
                </div>
                <div>
                    <label for="admin-password" class="admin-modal-label">Contraseña:</label>
                    <input type="password" id="admin-password" class="admin-modal-input">
                </div>
                <p id="admin-login-error" class="text-red-500 text-sm hidden">Usuario o contraseña incorrectos.</p>
            </div>
            <div class="flex justify-end space-x-3 mt-8">
                <button id="admin-login-cancel-btn" class="btn-secondary px-4 py-2 rounded-md text-sm">Cancelar</button>
                <button id="admin-login-submit-btn" class="btn-primary px-4 py-2 rounded-md text-sm">Ingresar</button>
            </div>
        </div>
    </div>

    <!-- Admin Panel Modal -->
    <div id="admin-panel-modal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-[150] hidden">
        <div class="bg-white p-6 rounded-lg shadow-xl w-11/12 max-w-4xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6 sticky top-0 bg-white py-3 z-10 border-b">
                <h3 class="text-2xl font-bold text-accent-pink">Panel de Administración</h3>
                <button id="admin-panel-close-btn" class="text-gray-500 hover:text-gray-800 text-3xl font-bold">&times;</button>
            </div>
            <p class="text-sm text-orange-600 bg-orange-100 p-3 rounded-md mb-4">
                <strong>Importante:</strong> Los cambios realizados aquí son temporales y solo para la sesión actual del navegador.
                Para guardar cambios permanentemente, se necesitaría una base de datos.
            </p>
            <div class="mb-6">
                <label class="admin-modal-label mb-2">Seleccionar Categoría para Editar:</label>
                <div id="admin-category-buttons" class="flex flex-wrap gap-2 justify-center">
                    <button type="button" class="btn-secondary text-sm px-4 py-2 rounded-md admin-category-btn" data-category-key="short">Pijamas Short</button>
                    <button type="button" class="btn-secondary text-sm px-4 py-2 rounded-md admin-category-btn" data-category-key="capri">Pijamas Capri</button>
                    <button type="button" class="btn-secondary text-sm px-4 py-2 rounded-md admin-category-btn" data-category-key="pantalon">Pijamas Pantalón</button>
                    <button type="button" class="btn-secondary text-sm px-4 py-2 rounded-md admin-category-btn" data-category-key="ninas">Pijamas Niñas</button>
                </div>
                <div class="mt-4 flex space-x-2">
                    <button id="admin-add-new-product-btn" class="btn-primary text-sm hidden">+ Añadir Nueva Pijama</button>
                    <button id="download-changes-report-btn" class="btn-info text-sm"><i class="fas fa-download mr-2"></i>Descargar Reporte de Cambios</button>
                </div>
            </div>

            <div id="admin-add-new-product-form-container" class="hidden mb-6">
                <!-- Form for adding new product will be injected here -->
            </div>

            <div id="admin-products-editor" class="space-y-6">
                <!-- Product editing forms will be injected here -->
            </div>
        </div>
    </div>


    <script>
        // Helper to extract number from product name for sorting
        function extractNumberFromName(name) {
            const match = name.match(/\d+/);
            return match ? parseInt(match[0]) : Infinity; // Return Infinity for items without numbers to push them to end
        }

        // Product data (can be updated by admin in this session)
        let mockPajamasData = {
            short: {
                id: "pijamas-short",
                title: "Pijamas Short",
                description: "Ideales para noches cálidas. Diseños frescos y divertidos. Confeccionadas con telas suaves y transpirables.",
                items: [
                    { id: "short-new-1750174090398", name: "Pijama Short 1", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.44-PM-2.jpeg", tallas: [{size: "XL", stock: 5}, {size: "L", stock: 6}, {size: "M", stock: 6}, {size: "S", stock: 6}]},
                    { id: "short-2", name: "Pijama Short 2", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-09-at-11.08.27-AM-2.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}]}, // Modified
                    { id: "short-3", name: "Pijama Short 3", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-09-at-11.08.28-AM.jpeg", tallas: [{size: "M", stock: 5}, {size: "S", stock: 5}]}, // Modified
                    { id: "short-new-1750174993447", name: "Pijama Short 4", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.44-PM-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 10}, {size: "L", stock: 12}, {size: "XL", stock: 10}]},
                    { id: "short-new-1750193705854", name: "Pijama Short 5", image: "https://textilesmay.shop/wp-content/uploads/2025/04/WhatsApp-Image-2025-03-31-at-11.56.31-AM.jpeg", tallas: [{size: "M", stock: 8}]}, // Added
                    { id: "short-6", name: "Pijama Short 6", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-11.11.29-AM.jpeg", tallas: [{size: "XL", stock: 10}, {size: "L", stock: 17}, {size: "M", stock: 16}]},
                    { id: "short-7", name: "Pijama Short 7", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.53.59-AM.jpeg", tallas: [{size: "XL", stock: 9}, {size: "L", stock: 6}, {size: "M", stock: 15}]},
                    { id: "short-8", name: "Pijama Short 8", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.00-AM.jpeg", tallas: [{size: "XL", stock: 6}, {size: "L", stock: 13}, {size: "M", stock: 3}, {size: "S", stock: 10}]},
                    { id: "short-9", name: "Pijama Short 9", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.00-AM-1.jpeg", tallas: [{size: "XL", stock: 2}, {size: "L", stock: 4}, {size: "S", stock: 16}]},
                    { id: "short-10", name: "Pijama Short 10", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.00-AM-2.jpeg", tallas: [{size: "L", stock: 21}, {size: "M", stock: 7}]},
                    { id: "short-11", name: "Pijama Short 11", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.01-AM.jpeg", tallas: [{size: "L", stock: 20}, {size: "M", stock: 26}]},
                    { id: "short-12", name: "Pijama Short 12", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.01-AM-1.jpeg", tallas: [{size: "XL", stock: 6}, {size: "L", stock: 21}, {size: "M", stock: 11}]},
                    { id: "short-13", name: "Pijama Short 13", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.02-AM.jpeg", tallas: [{size: "XL", stock: 6}, {size: "L", stock: 18}, {size: "M", stock: 12}]},
                    { id: "short-15", name: "Pijama Short 15", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.02-AM-2.jpeg", tallas: [{size: "XL", stock: 16}, {size: "L", stock: 26}, {size: "M", stock: 13}, {size: "S", stock: 11}]},
                    { id: "short-16", name: "Pijama Short 16", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.03-AM.jpeg", tallas: [{size: "XL", stock: 13}, {size: "L", stock: 23}, {size: "M", stock: 16}, {size: "S", stock: 20}]},
                    { id: "short-17", name: "Pijama Short 17", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.03-AM-1.jpeg", tallas: [{size: "L", stock: 23}, {size: "M", stock: 17}, {size: "S", stock: 12}]},
                    { id: "short-18", name: "Pijama Short 18", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.04-AM.jpeg", tallas: [{size: "XL", stock: 13}, {size: "S", stock: 7}]},
                    { id: "short-19", name: "Pijama Short 19", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.04-AM-1.jpeg", tallas: [{size: "M", stock: 9}, {size: "S", stock: 15}]},
                    { id: "short-20", name: "Pijama Short 20", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.05-AM.jpeg", tallas: [{size: "XL", stock: 13}, {size: "M", stock: 19}, {size: "L", stock: 24}]},
                    { id: "short-22", name: "Pijama Short 22", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.05-AM-2.jpeg", tallas: [{size: "S", stock: 16}]},
                    { id: "short-23", name: "Pijama Short 23", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.07-AM.jpeg", tallas: [{size: "S", stock: 16}, {size: "M", stock: 10}, {size: "L", stock: 22}, {size: "XL", stock: 14}]},
                    { id: "short-24", name: "Pijama Short 24", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.07-AM-1.jpeg", tallas: [{size: "XL", stock: 17}, {size: "L", stock: 26}, {size: "M", stock: 12}, {size: "S", stock: 16}]},
                    { id: "short-25", name: "Pijama Short 25", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.07-AM-2.jpeg", tallas: [{size: "XL", stock: 13}, {size: "L", stock: 27}, {size: "M", stock: 15}, {size: "S", stock: 5}]},
                    { id: "short-26", name: "Pijama Short 26", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.08-AM.jpeg", tallas: [{size: "XL", stock: 5}, {size: "S", stock: 6}]},
                    { id: "short-27", name: "Pijama Short 27", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.08-AM-1.jpeg", tallas: [{size: "XL", stock: 13}, {size: "L", stock: 14}]}, // Modified
                    { id: "short-28", name: "Pijama Short 28", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.08-AM-2.jpeg", tallas: [{size: "XL", stock: 13}, {size: "L", stock: 20}, {size: "M", stock: 4}, {size: "S", stock: 14}]},
                    { id: "short-29", name: "Pijama Short 29", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.54.09-AM-1.jpeg", tallas: [{size: "L", stock: 14}, {size: "S", stock: 12}]},
                    { id: "short-new-1750175263442", name: "Pijama Short 30", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.43-PM-2.jpeg", tallas: [{size: "S", stock: 12}, {size: "M", stock: 12}, {size: "L", stock: 16}, {size: "XL", stock: 12}]},
                    // short-new-1750175418762 (Pijama Short 31) removed
                    { id: "short-new-1750175495869", name: "Pijama Short 32", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.43-PM-1.jpeg", tallas: [{size: "S", stock: 10}, {size: "M", stock: 10}, {size: "L", stock: 10}, {size: "XL", stock: 10}]},
                    { id: "short-new-1750175571418", name: "Pijama Short 33", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.43-PM.jpeg", tallas: [{size: "S", stock: 12}, {size: "M", stock: 10}, {size: "L", stock: 8}, {size: "XL", stock: 7}]},
                    { id: "short-new-1750175626731", name: "Pijama Short 34", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.42-PM-1.jpeg", tallas: [{size: "S", stock: 10}, {size: "M", stock: 12}, {size: "L", stock: 12}, {size: "XL", stock: 6}]},
                    { id: "short-new-1750175669814", name: "Pijama Short 35", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.42-PM.jpeg", tallas: [{size: "S", stock: 12}, {size: "M", stock: 12}, {size: "L", stock: 12}, {size: "XL", stock: 12}]},
                    { id: "short-new-1750175709545", name: "Pijama Short 36", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.35-AM-2.jpeg", tallas: [{size: "S", stock: 12}]},
                    { id: "short-new-1750175814257", name: "Pijama Short 37", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.35-AM.jpeg", tallas: [{size: "S", stock: 12}]},
                    { id: "short-new-1750175899401", name: "Pijama Short 38", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.34-AM.jpeg", tallas: [{size: "S", stock: 15}]},
                    { id: "short-new-1750175979406", name: "Pijama Short 39", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.33-AM-2.jpeg", tallas: [{size: "S", stock: 6}, {size: "M", stock: 6}]}, // Modified
                    { id: "short-new-1750176001513", name: "Pijama Short 40", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.33-AM-1.jpeg", tallas: [{size: "S", stock: 8}]},
                    { id: "short-new-1750176038759", name: "Pijama Short 41", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-17-at-10.22.33-AM.jpeg", tallas: [{size: "S", stock: 15}]},
                ].sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)) // Sort short category
            },
            capri: {
                id: "pijamas-capri",
                title: "Pijamas Capri",
                description: "La opción perfecta para entretiempo. Cobertura ideal y ligereza. Diseños versátiles para cualquier momento del día.",
                items: [
                    { id: "capri-2", name: "Pijama Capri 8", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.24.43-PM.jpeg", tallas: [{size: "S", stock: 3}]},
                    { id: "capri-4", name: "Pijama Capri 10", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.25.02-PM.jpeg", tallas: [{size: "S", stock: 1}]},
                    { id: "capri-6", name: "Pijama Capri 6", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.25.53-PM.jpeg", tallas: [{size: "S", stock: 2}]},
                    { id: "capri-7", name: "Pijama Capri 7", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.25.58-PM.jpeg", tallas: [{size: "S", stock: 4}]},
                    { id: "capri-new-1750176403999", name: "Pijama Capri 1", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.47-PM-2-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    // capri-new-1750176555240 (Pijama Capri 3) removed
                    { id: "capri-new-1750176736939", name: "Pijama Capri 2", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.47-PM-1-1.jpeg", tallas: [{size: "S", stock: 10}, {size: "M", stock: 10}, {size: "L", stock: 10}, {size: "XL", stock: 10}]},
                    { id: "capri-new-1750177124320", name: "Pijama Capri 4", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.46-PM.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "capri-new-1750177192545", name: "Pijama Capri 11", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.47-PM.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "capri-new-1750177243797", name: "Pijama Capri 12", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.45-PM-3.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "capri-new-1750177279261", name: "Pijama Capri 13", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.45-PM-2.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "capri-new-1750177314704", name: "Pijama Capri 14", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.45-PM-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "capri-new-1750177349174", name: "Pijama Capri 15", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.45-PM.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    // Moved from short and renamed
                    { id: "short-new-1750175053206", name: "Pijama Capri 3", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.44-PM.jpeg", tallas: [{size: "S", stock: 10}, {size: "M", stock: 12}, {size: "L", stock: 12}, {size: "XL", stock: 10}]},
                ].sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)) // Sort capri category
            },
            pantalon: {
                id: "pijamas-pantalon",
                title: "Pijamas Pantalón",
                description: "Máxima comodidad y calidez para tus noches. Estampados exclusivos. Materiales premium para un descanso ideal.",
                items: [
                    { id: "pantalon-new-1750179045801", name: "Pijama Pantalón 1", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.23.14-PM-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "pantalon-new-1750179466238", name: "Pijama Pantalón 2", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.48-PM-1-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "pantalon-new-1750179087726", name: "Pijama Pantalón 3", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.23.14-PM.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]},
                    { id: "pantalon-new-1750179156208", name: "Pijama Pantalón 4", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.49-PM-3.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 6
                    { id: "pantalon-7", name: "Pijama Pantalón 5", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.34-PM.jpeg", tallas: [{size: "S", stock: 5}, {size: "XL", stock: 1}]}, // Renamed from Pantalon 7
                    { id: "pantalon-9", name: "Pijama Pantalón 6", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.34-PM-2.jpeg", tallas: [{size: "S", stock: 7}]}, // Renamed from Pantalon 9
                    { id: "pantalon-new-1750179201005", name: "Pijama Pantalón 7", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.49-PM-2.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 10
                    { id: "pantalon-new-1750179245489", name: "Pijama Pantalón 8", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.49-PM-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 11
                    { id: "pantalon-5", name: "Pijama Pantalón 9", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.31-PM.jpeg", tallas: [{size: "S", stock: 4}]}, // Renamed from Pantalon 5
                    { id: "pantalon-new-1750179280249", name: "Pijama Pantalón 10", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.48-PM-2-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 12
                    { id: "pantalon-4", name: "Pijama Pantalón 11", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.29-PM.jpeg", tallas: [{size: "S", stock: 5}]}, // Renamed from Pantalon 13
                    { id: "pantalon-new-1750179405571", name: "Pijama Pantalón 12", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.48-PM-3-1.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 13
                    { id: "pantalon-2", name: "Pijama Pantalón 13", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-05-at-10.47.07-AM.jpeg", tallas: [{size: "S", stock: 5}]}, // Renamed from Pantalon 14
                    { id: "pantalon-8", name: "Pijama Pantalón 14", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-04-at-2.26.34-PM-1.jpeg", tallas: [{size: "S", stock: 5}]}, // Renamed from Pantalon 15
                    { id: "pantalon-new-1750179624068", name: "Pijama Pantalón 15", image: "https://textilesmay.shop/wp-content/uploads/2025/06/WhatsApp-Image-2025-06-16-at-5.22.48-PM-4.jpeg", tallas: [{size: "S", stock: 8}, {size: "M", stock: 8}, {size: "L", stock: 8}, {size: "XL", stock: 8}]}, // Renamed from Pantalon 16
                ].sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)) // Sort pantalon category
            },
            ninas: {
                id: "pijamas-ninas",
                title: "Pijamas Niñas",
                description: "Diseños adorables y tejidos suaves para las más pequeñas. Comodidad y diversión con estampados llenos de magia.",
                items: [
                    { id: "ninas-2", name: "Pijama Niña 2", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.52.18-PM-1.jpeg", tallas: [{size: "6", stock: 7}]},
                    { id: "ninas-3", name: "Pijama Niña 3", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.52.18-PM-2.jpeg", tallas: [{size: "4", stock: 8}]}, // Modified
                    { id: "ninas-5", name: "Pijama Niña 5", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.52.19-PM-1.jpeg", tallas: [{size: "4", stock: 6}]},
                    { id: "ninas-7", name: "Pijama Niña 7", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.52.19-PM-3.jpeg", tallas: [{size: "4", stock: 4}]},
                    { id: "ninas-8", name: "Pijama Niña 8", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.32-PM.jpeg", tallas: [{size: "4", stock: 7}, {size: "6", stock: 4}, {size: "10", stock: 1}]},
                    { id: "ninas-9", name: "Pijama Niña 9", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.33-PM.jpeg", tallas: [{size: "10", stock: 7}]},
                    { id: "ninas-10", name: "Pijama Niña 10", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.34-PM.jpeg", tallas: [{size: "10", stock: 3}]},
                    { id: "ninas-11", name: "Pijama Niña 11", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.34-PM-1.jpeg", tallas: [{size: "10", stock: 5}]},
                    { id: "ninas-13", name: "Pijama Niña 13", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.35-PM.jpeg", tallas: [{size: "10", stock: 7}]},
                    { id: "ninas-14", name: "Pijama Niña 14", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.35-PM-1.jpeg", tallas: [{size: "10", stock: 6}]},
                    { id: "ninas-15", name: "Pijama Niña 15", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.35-PM-2.jpeg", tallas: [{size: "4", stock: 7}, {size: "6", stock: 5}, {size: "10", stock: 5}]},
                    { id: "ninas-16", name: "Pijama Niña 16", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.35-PM-3.jpeg", tallas: [{size: "4", stock: 9}, {size: "6", stock: 4}, {size: "6", stock: 7}]},
                    { id: "ninas-17", name: "Pijama Niña 17", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.36-PM.jpeg", tallas: [{size: "4", stock: 7}, {size: "6", stock: 4}, {size: "10", stock: 4}]},
                    { id: "ninas-18", name: "Pijama Niña 18", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.36-PM-1.jpeg", tallas: [{size: "4", stock: 9}, {size: "6", stock: 8}, {size: "10", stock: 3}]},
                    { id: "ninas-19", name: "Pijama Niña 19", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.37-PM.jpeg", tallas: [{size: "4", stock: 9}, {size: "6", stock: 3}]},
                    { id: "ninas-20", name: "Pijama Niña 20", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.37-PM-1.jpeg", tallas: [{size: "4", stock: 10}, {size: "6", stock: 7}]},
                    { id: "ninas-21", name: "Pijama Niña 21", image: "https://textilesmay.shop/wp-content/uploads/2025/05/WhatsApp-Image-2025-05-20-at-3.29.37-PM-2.jpeg", tallas: [{size: "4", stock: 10}, {size: "6", stock: 4}, {size: "10", stock: 2}]},
                ].sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)) // Sort ninas category
            }
        };

        let cartItems = [];
        let adminChangesLog = [];

        const customAlertModal = document.getElementById('custom-alert-modal');
        const customAlertTitle = document.getElementById('custom-alert-title');
        const customAlertMessage = document.getElementById('custom-alert-message');
        const customAlertButtons = document.getElementById('custom-alert-buttons');

        function showAlert(message, title = "Alerta", confirmCallback = null, cancelCallback = null) {
            if (!customAlertModal || !customAlertTitle || !customAlertMessage || !customAlertButtons) {
                if (confirmCallback && window.confirm(message)) {
                    confirmCallback();
                } else if (!confirmCallback) {
                    alert(message);
                }
                return;
            }

            customAlertTitle.textContent = title;
            customAlertMessage.textContent = message;
            customAlertButtons.innerHTML = '';

            if (confirmCallback) {
                const confirmBtn = document.createElement('button');
                confirmBtn.textContent = 'Confirmar';
                confirmBtn.className = 'btn-danger px-6 py-2 rounded-lg font-semibold';
                confirmBtn.addEventListener('click', () => {
                    confirmCallback();
                    closeCustomAlert();
                });
                customAlertButtons.appendChild(confirmBtn);

                const cancelBtn = document.createElement('button');
                cancelBtn.textContent = 'Cancelar';
                cancelBtn.className = 'btn-secondary px-6 py-2 rounded-lg font-semibold';
                cancelBtn.addEventListener('click', () => {
                    if (cancelCallback) cancelCallback();
                    closeCustomAlert();
                });
                customAlertButtons.appendChild(cancelBtn);
            } else {
                const closeBtn = document.createElement('button');
                closeBtn.id = 'custom-alert-close-btn-dynamic';
                closeBtn.textContent = 'Entendido';
                closeBtn.className = 'btn-primary px-6 py-2 rounded-lg font-semibold';
                closeBtn.addEventListener('click', closeCustomAlert);
                customAlertButtons.appendChild(closeBtn);
            }

            customAlertModal.classList.remove('hidden');
            setTimeout(() => {
                customAlertModal.classList.add('opacity-100');
                customAlertModal.querySelector('.transform').classList.remove('scale-95');
                customAlertModal.querySelector('.transform').classList.add('scale-100');
            }, 10);
        }

        function closeCustomAlert() {
            if (customAlertModal) {
                customAlertModal.classList.remove('opacity-100');
                customAlertModal.querySelector('.transform').classList.remove('scale-100');
                customAlertModal.querySelector('.transform').classList.add('scale-95');
                setTimeout(() => {
                    customAlertModal.classList.add('hidden');
                }, 300);
            }
        }
        const staticCloseBtn = document.getElementById('custom-alert-close-btn');
        if(staticCloseBtn) staticCloseBtn.addEventListener('click', closeCustomAlert);


        function findProductById(productId) {
            for (const categoryKey in mockPajamasData) {
                const category = mockPajamasData[categoryKey];
                const foundItem = category.items.find(item => item.id === productId);
                if (foundItem) return foundItem;
            }
            return null;
        }

        function addToCart(productId, selectedSize, quantity) {
            const product = findProductById(productId);
            if (!product) { showAlert('Error: Producto no encontrado.'); return; }
            const sizeDetails = product.tallas.find(t => t.size === selectedSize);
            if (!sizeDetails) { showAlert('Error: Talla no disponible.'); return; }
            const availableStock = sizeDetails.stock;
            if (availableStock === 0) { showAlert(`Lo sentimos, la talla ${selectedSize} para ${product.name} está agotada.`); return; }
            if (quantity <= 0) { showAlert('Por favor, ingresa una cantidad válida.'); return; }

            const existingCartItemIndex = cartItems.findIndex(item => item.productId === productId && item.selectedSize === selectedSize);
            if (existingCartItemIndex > -1) {
                const currentCartQuantity = cartItems[existingCartItemIndex].selectedQuantity;
                if (currentCartQuantity + quantity > availableStock) {
                    showAlert(`No hay suficiente stock. Solo quedan ${availableStock - currentCartQuantity} unidades.`); return;
                }
                cartItems[existingCartItemIndex].selectedQuantity += quantity;
            } else {
                if (quantity > availableStock) {
                    showAlert(`No hay suficiente stock. Solo hay ${availableStock} unidades.`); return;
                }
                cartItems.push({ productId, name: product.name, image: product.image, selectedSize, selectedQuantity: quantity, availableStock });
            }
            updateCartDisplay();
            showAlert(`${quantity} x ${product.name} (Talla: ${selectedSize}) añadido al carrito.`, "¡Producto Añadido!");
        }

        function updateCartItemQuantity(productId, selectedSize, newQuantity) {
            const itemIndex = cartItems.findIndex(item => item.productId === productId && item.selectedSize === selectedSize);
            if (itemIndex > -1) {
                const product = findProductById(productId);
                const sizeDetails = product.tallas.find(t => t.size === selectedSize);
                if (!sizeDetails) return;
                const maxStock = sizeDetails.stock;
                if (newQuantity > maxStock) {
                    cartItems[itemIndex].selectedQuantity = maxStock;
                    showAlert(`Solo hay ${maxStock} unidades disponibles.`);
                } else if (newQuantity < 1) {
                    removeCartItem(productId, selectedSize);
                } else {
                    cartItems[itemIndex].selectedQuantity = newQuantity;
                }
                updateCartDisplay();
            }
        }

        function removeCartItem(productId, selectedSize) {
            const itemToRemove = cartItems.find(item => item.productId === productId && item.selectedSize === selectedSize);
            cartItems = cartItems.filter(item => !(item.productId === productId && item.selectedSize === selectedSize));
            updateCartDisplay();
            if (itemToRemove) showAlert(`${itemToRemove.name} (Talla: ${itemToRemove.selectedSize}) eliminado.`, "Producto Eliminado");
        }

        function updateCartDisplay() {
            const cartCountBadge = document.getElementById('cart-count-badge');
            let totalItemsInCart = cartItems.reduce((sum, item) => sum + item.selectedQuantity, 0);
            if (cartCountBadge) {
                cartCountBadge.textContent = totalItemsInCart;
                cartCountBadge.classList.toggle('hidden', totalItemsInCart === 0);
                if (totalItemsInCart > 0) {
                    cartCountBadge.classList.add('cart-count-badge-animated');
                    cartCountBadge.addEventListener('animationend', () => cartCountBadge.classList.remove('cart-count-badge-animated'), { once: true });
                }
            }
            renderCartModal();
        }

        function renderCartModal() {
            const cartItemsDisplay = document.getElementById('cart-items-display');
            const cartEmptyMessage = document.getElementById('cart-empty-message');
            if (!cartItemsDisplay || !cartEmptyMessage) return;
            cartItemsDisplay.innerHTML = '';
            if (cartItems.length === 0) {
                cartEmptyMessage.classList.remove('hidden');
            } else {
                cartEmptyMessage.classList.add('hidden');
                cartItems.forEach(item => {
                    const product = findProductById(item.productId);
                    const sizeDetails = product ? product.tallas.find(t => t.size === item.selectedSize) : null;
                    const currentStockForSize = sizeDetails ? sizeDetails.stock : 'N/A';
                    const cartItemHtml = `
                        <div class="flex items-center space-x-3 sm:space-x-4 border-b border-pink-100 pb-4 last:border-b-0">
                            <img src="${item.image}" alt="${item.name}" class="w-16 h-16 sm:w-20 sm:h-20 object-cover rounded-md shadow" onerror="this.onerror=null;this.src='https://placehold.co/80x80/FFC0CB/333?text=Pijama';">
                            <div class="flex-grow">
                                <h4 class="font-semibold text-md sm:text-lg text-slate-800">${item.name}</h4>
                                <p class="text-xs sm:text-sm text-slate-600">Talla: ${item.selectedSize}</p>
                                <p class="text-xs sm:text-sm text-slate-500">Stock: ${currentStockForSize}</p>
                            </div>
                            <div class="flex items-center space-x-1 sm:space-x-2">
                                <button class="cart-qty-btn bg-pink-200 text-accent-pink w-7 h-7 sm:w-8 sm:h-8 rounded-md hover:bg-pink-300 text-lg sm:text-xl flex items-center justify-center"
                                        data-action="decrease" data-product-id="${item.productId}" data-size="${item.selectedSize}">-</button>
                                <span class="font-bold text-slate-800 w-8 text-center text-sm sm:text-base">${item.selectedQuantity}</span>
                                <button class="cart-qty-btn bg-pink-200 text-accent-pink w-7 h-7 sm:w-8 sm:h-8 rounded-md hover:bg-pink-300 text-lg sm:text-xl flex items-center justify-center"
                                        data-action="increase" data-product-id="${item.productId}" data-size="${item.selectedSize}">+</button>
                            </div>
                            <button class="remove-from-cart-btn text-red-500 hover:text-red-700 text-xl sm:text-2xl p-1"
                                        data-product-id="${item.productId}" data-size="${item.selectedSize}">&times;</button>
                        </div>`;
                    cartItemsDisplay.innerHTML += cartItemHtml;
                });
            }
        }

        function renderAllProductSections() {
            const productSectionsContainer = document.getElementById('product-sections-container');
            if (!productSectionsContainer) {
                console.error("El contenedor de secciones de productos no fue encontrado.");
                return;
            }
            productSectionsContainer.innerHTML = '';

            // Render Short, Capri, Pantalon, and Niñas as separate sections
            productSectionsContainer.innerHTML += createProductSectionHTML(mockPajamasData.short);
            productSectionsContainer.innerHTML += createProductSectionHTML(mockPajamasData.capri);
            productSectionsContainer.innerHTML += createProductSectionHTML(mockPajamasData.pantalon);
            productSectionsContainer.innerHTML += createProductSectionHTML(mockPajamasData.ninas);

            // Initialize sliders for each section
            initializeProductSliders();
            addEventListenersForProductInteractions();
        }

        function createProductSectionHTML(category) {
            if (!category || !category.items) return '';

            const itemsHtml = category.items.map((item) => {
                const firstTalla = (item.tallas && item.tallas.length > 0) ? item.tallas.find(t => t.stock > 0) || item.tallas[0] : {size: "", stock: 0};
                const firstTallaStock = firstTalla.stock;
                const tallaOptions = (item.tallas && item.tallas.length > 0)
                    ? item.tallas.map(talla => `<option value="${talla.size}" data-stock="${talla.stock}" ${talla.stock === 0 ? 'disabled class="text-red-500"' : ''}>${talla.size} (${talla.stock} UND)${talla.stock === 0 ? ' - Agotado' : ''}</option>`).join('')
                    : '<option value="" data-stock="0" disabled>No disponible</option>';
                const isOutOfStock = item.tallas.every(t => t.stock === 0);

                return `
                    <div class="product-slider-item">
                        <img src="${item.image}" alt="${item.name}" class="w-full h-auto object-cover rounded-lg shadow-xl mx-auto aspect-[3/4]" onerror="this.onerror=null;this.src='https://placehold.co/320x427/FFC0CB/333?text=Pijama';">
                        <div class="text-center mt-3 p-3 bg-white/80 backdrop-blur-sm rounded-lg shadow-md">
                            <h4 class="text-lg font-semibold text-accent-pink truncate" title="${item.name}">${item.name}</h4>
                            ${isOutOfStock ? '<p class="text-sm text-red-500 font-semibold mt-1">Agotado</p>' : ''}
                            <div class="flex flex-col items-center space-y-2 mt-2">
                                <div class="flex items-center space-x-2 w-full justify-center">
                                    <label for="size-select-${item.id}" class="text-sm text-slate-700 sr-only">Talla:</label>
                                    <select id="size-select-${item.id}" class="border border-pink-300 rounded-md p-2 text-sm w-full max-w-[150px] focus:ring-accent-pink focus:border-accent-pink" ${isOutOfStock ? 'disabled' : ''}>${tallaOptions}</select>
                                </div>
                                <div class="flex items-center space-x-2 w-full justify-center">
                                    <label for="quantity-input-${item.id}" class="text-sm text-slate-700 sr-only">Cant:</label>
                                    <input type="number" id="quantity-input-${item.id}" value="${firstTallaStock > 0 ? 1 : 0}" min="${firstTallaStock > 0 ? 1 : 0}" max="${firstTallaStock}" class="w-20 border border-pink-300 rounded-md p-2 text-sm text-center focus:ring-accent-pink focus:border-accent-pink" ${isOutOfStock || firstTallaStock === 0 ? 'disabled' : ''}>
                                </div>
                                <button class="add-to-cart-btn btn-primary px-4 py-2 rounded-lg text-sm font-semibold transition-colors w-full max-w-[150px] shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
                                        data-product-id="${item.id}" ${isOutOfStock || firstTallaStock === 0 ? 'disabled' : ''}>
                                    Añadir al Carrito
                                </button>
                            </div>
                        </div>
                    </div>`;
            }).join('');

            let bgClass = '';
            if (category.id === 'pijamas-short') bgClass = 'section-bg-short';
            else if (category.id === 'pijamas-capri') bgClass = 'section-bg-capri';
            else if (category.id === 'pijamas-pantalon') bgClass = 'section-bg-pantalon';
            else if (category.id === 'pijamas-ninas') bgClass = 'section-bg-ninas';

            return `
                <section id="${category.id}" class="py-12 md:py-16 px-4 md:px-6 ${bgClass} shadow-inner">
                    <div class="section-overlay"></div>
                    <div class="container mx-auto section-content">
                        <h3 class="text-4xl md:text-5xl font-bold text-accent-pink text-center mb-6 md:mb-8">${category.title}</h3>
                        <p class="text-center text-lg text-slate-800 mb-10 max-w-2xl mx-auto">${category.description}</p>
                        <div class="product-slider-container mx-auto bg-pink-50 p-4 rounded-xl shadow-2xl">
                            <div class="product-slider-wrapper" id="${category.id}-product-slider-wrapper">
                                ${itemsHtml}
                            </div>
                            ${category.items.length > 1 ? `
                            <button class="slider-nav-btn slider-prev absolute top-1/2 left-0.5 sm:left-1 transform -translate-y-1/2 z-10 p-2 sm:p-3 text-xl flex items-center justify-center" data-target-id="${category.id}-product-slider-wrapper" data-direction="prev" aria-label="Anterior">❮</button>
                            <button class="slider-nav-btn slider-next absolute top-1/2 right-0.5 sm:right-1 transform -translate-y-1/2 z-10 p-2 sm:p-3 text-xl flex items-center justify-center" data-target-id="${category.id}-product-slider-wrapper" data-direction="next" aria-label="Siguiente">❯</button>` : ''}
                        </div>
                    </div>
                </section>`;
        }

        function initializeProductSliders() {
            document.querySelectorAll('.product-slider-container').forEach(container => {
                const wrapper = container.querySelector('.product-slider-wrapper');
                const prevButton = container.querySelector('.slider-prev');
                const nextButton = container.querySelector('.slider-next');

                if (!wrapper) return;

                let currentIndex = 0;
                const items = wrapper.querySelectorAll('.product-slider-item');
                const totalItems = items.length;

                // Adjust item width based on screen size for correct scrolling
                const updateItemWidth = () => {
                    let itemsPerView = 1;
                    if (window.innerWidth >= 768) { // md breakpoint
                        itemsPerView = 3;
                    } else if (window.innerWidth >= 640) { // sm breakpoint
                        itemsPerView = 2;
                    }

                    // Apply width to each item
                    items.forEach(item => {
                        item.style.width = `${100 / itemsPerView}%`;
                    });

                    // Recalculate and update position
                    updateSliderPosition();
                };

                const updateSliderPosition = () => {
                    if (items.length > 0) {
                        const itemWidth = items[0].offsetWidth; // Get computed width
                        wrapper.style.transform = `translateX(-${currentIndex * itemWidth}px)`;
                    }
                };

                const showNextItem = () => {
                    currentIndex = (currentIndex + 1) % totalItems;
                    updateSliderPosition();
                };

                const showPrevItem = () => {
                    currentIndex = (currentIndex - 1 + totalItems) % totalItems;
                    updateSliderPosition();
                };

                if (prevButton) {
                    prevButton.removeEventListener('click', showPrevItem); // Avoid multiple listeners
                    prevButton.addEventListener('click', showPrevItem);
                }
                if (nextButton) {
                    nextButton.removeEventListener('click', showNextItem); // Avoid multiple listeners
                    nextButton.addEventListener('click', showNextItem);
                }

                // Initial setup and on resize
                window.addEventListener('resize', updateItemWidth);
                updateItemWidth(); // Call initially
            });
        }


        function addEventListenersForProductInteractions() {
            document.querySelectorAll('.add-to-cart-btn').forEach(button => {
                const newButton = button.cloneNode(true);
                button.parentNode.replaceChild(newButton, button);
                newButton.addEventListener('click', handleAddToCartClick);
            });
            document.querySelectorAll('select[id^="size-select-"]').forEach(selectElement => {
                const newSelect = selectElement.cloneNode(true);
                selectElement.parentNode.replaceChild(newSelect, selectElement);
                newSelect.addEventListener('change', handleSizeChange);
            });
        }

        function handleAddToCartClick(event) {
            const button = event.target.closest('.add-to-cart-btn');
            if (!button) return;
            const productId = button.dataset.productId;
            const productCard = button.closest('.text-center');
            if (!productCard) { console.error('Contenedor de producto no encontrado.'); return; }
            const sizeSelect = productCard.querySelector(`select[id^="size-select-${productId}"]`);
            const quantityInput = productCard.querySelector(`input[type="number"][id^="quantity-input-${productId}"]`);
            if (sizeSelect && quantityInput) {
                const selectedSize = sizeSelect.value;
                const quantity = parseInt(quantityInput.value);
                const selectedOption = sizeSelect.options[sizeSelect.selectedIndex];
                const stockForSelectedSize = selectedOption ? parseInt(selectedOption.dataset.stock) : 0;
                if (!selectedSize) { showAlert("Por favor, selecciona una talla."); return; }
                if (selectedOption.disabled && stockForSelectedSize === 0) { showAlert(`Lo sentimos, la talla ${selectedSize} para ${product.name} está agotada.`); return; }
                if (quantity <= 0) { showAlert('Por favor, ingresa una cantidad válida.'); return; }
                if (quantity > stockForSelectedSize) { showAlert(`No puedes añadir más de ${stockForSelectedSize} unidades para la talla ${selectedSize}.`); return; }
                addToCart(productId, selectedSize, quantity);
            } else {
                console.error('Elementos de talla/cantidad no encontrados para:', productId);
                showAlert("Error al procesar. Intenta de nuevo.");
            }
        }

        function handleSizeChange(event) {
            const selectElement = event.target;
            const productId = selectElement.id.replace('size-select-', '');
            const selectedOption = selectElement.selectedOptions[0];
            const maxStock = selectedOption ? parseInt(selectedOption.dataset.stock) : 0;
            const productCard = selectElement.closest('.text-center');
            if (productCard) {
                const quantityInput = productCard.querySelector(`input[type="number"][id="quantity-input-${productId}"]`);
                const addButton = productCard.querySelector(`.add-to-cart-btn[data-product-id="${productId}"]`);
                if (quantityInput && addButton) {
                    quantityInput.max = maxStock;
                    if (maxStock === 0) {
                        quantityInput.value = 0; quantityInput.min = 0; quantityInput.disabled = true; addButton.disabled = true;
                    } else {
                        quantityInput.value = 1; quantityInput.min = 1; quantityInput.disabled = false; addButton.disabled = false;
                    }
                }
            }
        }

        // --- Admin Panel Logic ---
        const adminLoginBtn = document.getElementById('admin-login-btn');
        const adminLoginModal = document.getElementById('admin-login-modal');
        const adminLoginCancelBtn = document.getElementById('admin-login-cancel-btn');
        const adminLoginSubmitBtn = document.getElementById('admin-login-submit-btn');
        const adminUsernameInput = document.getElementById('admin-username');
        const adminPasswordInput = document.getElementById('admin-password');
        const adminLoginError = document.getElementById('admin-login-error');


        const adminPanelModal = document.getElementById('admin-panel-modal');
        const adminPanelCloseBtn = document.getElementById('admin-panel-close-btn');
        const adminProductsEditor = document.getElementById('admin-products-editor');
        const adminAddNewProductBtn = document.getElementById('admin-add-new-product-btn');
        const downloadChangesReportBtn = document.getElementById('download-changes-report-btn');

        // Global reference to the container for adding new product form
        const adminAddNewProductFormContainer = document.getElementById('admin-add-new-product-form-container');


        const ADMIN_USERNAME = "Textiles_May_Medellin";
        const ADMIN_PASSWORD = "Medellin2025***";

        if (adminLoginBtn) adminLoginBtn.addEventListener('click', () => adminLoginModal.classList.remove('hidden'));
        if (adminLoginCancelBtn) adminLoginCancelBtn.addEventListener('click', () => adminLoginModal.classList.add('hidden'));
        if (adminPanelCloseBtn) adminPanelCloseBtn.addEventListener('click', () => {
            adminPanelModal.classList.add('hidden');
            // Removed clearing adminChangesLog here to allow PDF download later
        });

        if (adminLoginSubmitBtn) {
            adminLoginSubmitBtn.addEventListener('click', () => {
                // Debugging logs
                console.log('Attempting admin login...');
                console.log('Entered Username:', adminUsernameInput.value);
                console.log('Entered Password:', adminPasswordInput.value);
                console.log('Expected Username:', ADMIN_USERNAME);
                console.log('Expected Password:', ADMIN_PASSWORD);

                if (adminUsernameInput.value === ADMIN_USERNAME && adminPasswordInput.value === ADMIN_PASSWORD) {
                    console.log('Admin login successful!');
                    adminLoginModal.classList.add('hidden');
                    adminLoginError.classList.add('hidden');
                    adminUsernameInput.value = '';
                    adminPasswordInput.value = '';
                    openAdminPanel();
                } else {
                    console.log('Admin login failed: Incorrect credentials.');
                    adminLoginError.classList.remove('hidden');
                }
            });
        }

        function populateAdminCategorySelect() {
            // This function is no longer needed as we use buttons for category selection.
            // Keeping it as a placeholder comment if it was referenced elsewhere by mistake.
        }

        function openAdminPanel() {
            // No need to populate dropdown, buttons handle selection
            adminProductsEditor.innerHTML = '';
            if (adminAddNewProductFormContainer) {
                adminAddNewProductFormContainer.innerHTML = '';
                adminAddNewProductFormContainer.classList.add('hidden');
            }
            adminAddNewProductBtn.classList.add('hidden');
            adminPanelModal.classList.remove('hidden');
            // Attach event listeners to category buttons when panel opens
            document.querySelectorAll('.admin-category-btn').forEach(button => {
                // Ensure event listener is added only once
                button.removeEventListener('click', handleAdminCategoryButtonClick);
                button.addEventListener('click', handleAdminCategoryButtonClick);
            });
        }

        // New function to handle category button clicks
        function handleAdminCategoryButtonClick(event) {
            const categoryKey = event.target.dataset.categoryKey;
            // Hide the "add new product" form when a new category is selected
            if (adminAddNewProductFormContainer) {
                adminAddNewProductFormContainer.innerHTML = '';
                adminAddNewProductFormContainer.classList.add('hidden');
            }
            // Show the "add new product" button and set its data-category-key
            if (categoryKey) {
                adminAddNewProductBtn.classList.remove('hidden');
                adminAddNewProductBtn.dataset.categoryKey = categoryKey; // Corrected: camelCase
            } else {
                adminAddNewProductBtn.classList.add('hidden');
            }
            loadProductsForEditing(categoryKey);
        }

        // Re-attach event listener for add new product button, now global
        if (adminAddNewProductBtn) {
            adminAddNewProductBtn.removeEventListener('click', handleAdminAddNewProductButtonClick); // Prevent multiple listeners
            adminAddNewProductBtn.addEventListener('click', handleAdminAddNewProductButtonClick);
        }

        function handleAdminAddNewProductButtonClick(event) {
            const categoryKey = event.target.dataset.categoryKey;
            if (categoryKey) {
                displayNewProductForm(categoryKey);
            }
        }

        function logAdminChange(type, productName, productId, field, oldValue, newValue, categoryTitle = '') {
            adminChangesLog.push({
                timestamp: new Date().toLocaleString('es-CO'),
                type: type,
                productName: productName,
                productId: productId,
                category: categoryTitle,
                field: field,
                oldValue: oldValue,
                newValue: newValue
            });
            console.log("Admin Change Logged:", adminChangesLog[adminChangesLog.length - 1]); // Debug log
        }


        function displayNewProductForm(categoryKey) {
            if (!adminAddNewProductFormContainer) return;

            adminAddNewProductFormContainer.innerHTML = '';
            adminAddNewProductFormContainer.classList.remove('hidden');

            const newProductId = `${categoryKey}-new-${Date.now()}`;

            const formCard = document.createElement('div');
            formCard.id = `new-product-form-${newProductId}`;
            formCard.className = 'admin-product-card bg-pink-100 p-4 rounded-lg shadow mt-4 border border-accent-pink';
            formCard.innerHTML = `
                <h4 class="text-xl font-semibold text-accent-pink mb-3">Añadir Nueva Pijama a "${mockPajamasData[categoryKey].title}"</h4>
                <div class="mb-3">
                    <label for="new-name-${newProductId}" class="admin-modal-label">Nombre de la Pijama:</label>
                    <input type="text" id="new-name-${newProductId}" placeholder="Ej: Pijama Luna Mágica" class="admin-modal-input">
                </div>
                <div class="mb-3">
                    <label for="new-img-${newProductId}" class="admin-modal-label">URL de Imagen:</label>
                    <input type="url" id="new-img-${newProductId}" placeholder="https://ejemplo.com/imagen.jpg" class="admin-modal-input">
                </div>
                <div class="mb-3">
                    <h5 class="text-md font-semibold text-slate-700 mb-2">Tallas y Stock Iniciales:</h5>
                    <div id="new-tallas-editor-${newProductId}" class="space-y-2">
                        <div class="admin-talla-item" data-talla-index="0">
                            <input type="text" placeholder="Talla (ej. S)" class="admin-modal-input w-1/3 new-talla-size-input">
                            <input type="number" placeholder="Stock" min="0" class="admin-modal-input w-1/3 new-talla-stock-input">
                            <button class="remove-new-talla-btn text-red-500 hover:text-red-700 p-1" data-talla-index="0">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                    </div>
                    <button class="add-new-talla-btn mt-2 text-sm btn-secondary px-3 py-1 rounded-md" data-editor-id="new-tallas-editor-${newProductId}">+ Añadir Talla</button>
                </div>
                <div class="flex justify-end space-x-2 mt-4">
                    <button class="cancel-new-product-btn btn-secondary text-sm">Cancelar</button>
                    <button class="save-new-product-btn btn-primary text-sm" data-category-key="${categoryKey}" data-new-product-id="${newProductId}">Guardar Nueva Pijama</button>
                </div>
            `;
            adminAddNewProductFormContainer.appendChild(formCard);

            formCard.querySelector('.add-new-talla-btn').addEventListener('click', handleAddNewTallaFieldForNewProduct);
            formCard.querySelectorAll('.remove-new-talla-btn').forEach(btn => btn.addEventListener('click', handleRemoveNewTallaField));
            formCard.querySelector('.save-new-product-btn').addEventListener('click', handleSaveNewPijama);
            formCard.querySelector('.cancel-new-product-btn').addEventListener('click', () => {
                adminAddNewProductFormContainer.innerHTML = '';
                adminAddNewProductFormContainer.classList.add('hidden');
            });
        }

        function handleAddNewTallaFieldForNewProduct(event) {
            const button = event.target.closest('.add-new-talla-btn');
            const editorId = button.dataset.editorId;
            const tallasEditorDiv = document.getElementById(editorId);
            const newItemIndex = tallasEditorDiv.children.length;

            const newTallaDiv = document.createElement('div');
            newTallaDiv.className = 'admin-talla-item';
            newTallaDiv.dataset.tallaIndex = newItemIndex;
            newTallaDiv.innerHTML = `
                <input type="text" placeholder="Talla" class="admin-modal-input w-1/3 new-talla-size-input">
                <input type="number" placeholder="Stock" min="0" class="admin-modal-input w-1/3 new-talla-stock-input">
                <button class="remove-new-talla-btn text-red-500 hover:text-red-700 p-1" data-talla-index="0">
                                <i class="fas fa-trash-alt"></i>
                            </button>
            `;
            tallasEditorDiv.appendChild(newTallaDiv);
            newTallaDiv.querySelector('.remove-new-talla-btn').addEventListener('click', handleRemoveNewTallaField);
        }

        function handleRemoveNewTallaField(event) {
            const button = event.target.closest('.remove-new-talla-btn');
            button.parentElement.remove();
        }

        function handleSaveNewPijama(event) {
            const button = event.target.closest('.save-new-product-btn');
            const categoryKey = button.dataset.categoryKey;
            const newProductId = button.dataset.newProductId;

            const formContainer = document.getElementById(`new-product-form-${newProductId}`);
            const newNameInput = formContainer.querySelector(`#new-name-${newProductId}`);
            const newImageUrlInput = formContainer.querySelector(`#new-img-${newProductId}`);

            const newName = newNameInput.value.trim();
            const newImage = newImageUrlInput.value.trim();

            if (!newName) { showAlert("El nombre de la pijama es obligatorio.", "Error"); return; }
            if (!newImage) { showAlert("La URL de la imagen es obligatoria.", "Error"); return; }
            try { new URL(newImage); } catch (_) { showAlert("La URL de la imagen no es válida.", "Error"); return; }

            const newTallas = [];
            const tallasEditorDiv = formContainer.querySelector(`#new-tallas-editor-${newProductId}`);
            tallasEditorDiv.querySelectorAll('.admin-talla-item').forEach(tallaDiv => {
                const sizeInput = tallaDiv.querySelector('.new-talla-size-input');
                const stockInput = tallaDiv.querySelector('.new-talla-stock-input');
                if (sizeInput && stockInput && sizeInput.value.trim() !== "") {
                    newTallas.push({
                        size: sizeInput.value.trim(),
                        stock: parseInt(stockInput.value) || 0
                    });
                }
            });

            console.log("Collected newTallas for new product:", newTallas); // Debug log

            if (newTallas.length === 0) {
                showAlert("Debes añadir al menos una talla y stock para la nueva pijama.", "Error");
                return;
            }

            const newProduct = {
                id: newProductId,
                name: newName,
                image: newImage,
                tallas: newTallas
            };

            mockPajamasData[categoryKey].items.push(newProduct);
            mockPajamasData[categoryKey].items.sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name));


            logAdminChange("AÑADIDO", newName, newProductId, "Pijama completa", "-", JSON.stringify(newProduct, null, 2), mockPajamasData[categoryKey].title);
            showAlert(`Nueva pijama "${newName}" añadida a ${mockPajamasData[categoryKey].title}.`, "Pijama Añadida");

            if (adminAddNewProductFormContainer) {
                adminAddNewProductFormContainer.innerHTML = '';
                adminAddNewProductFormContainer.classList.add('hidden');
            }

            renderAllProductSections();
            loadProductsForEditing(categoryKey);
        }


        function loadProductsForEditing(categoryKey) {
            adminProductsEditor.innerHTML = '';
            if (!categoryKey) {
                if (adminAddNewProductBtn) adminAddNewProductBtn.classList.add('hidden');
                return;
            }
            if (adminAddNewProductBtn) adminAddNewProductBtn.classList.remove('hidden');
            if (adminAddNewProductBtn) adminAddNewProductBtn.dataset.categoryKey = categoryKey;

            let itemsToEdit = mockPajamasData[categoryKey] ? mockPajamasData[categoryKey].items : [];

            itemsToEdit.forEach((item, itemIndex) => {
                const productCard = document.createElement('div');
                productCard.className = 'admin-product-card';
                productCard.innerHTML = `
                    <div class="flex justify-between items-start mb-3">
                        <input type="text" id="name-${item.id}" value="${item.name}" class="admin-modal-input text-xl font-semibold text-accent-pink flex-grow mr-2" placeholder="Nombre de la Pijama">
                        <button class="delete-product-btn btn-danger text-xs px-2 py-1" data-item-id="${item.id}" data-category-key="${categoryKey}" data-item-index="${itemIndex}" data-item-name="${item.name}">
                            <i class="fas fa-trash-alt"></i> Eliminar
                        </button>
                    </div>
                    <div class="mb-3">
                        <label for="img-${item.id}" class="admin-modal-label">URL de Imagen:</label>
                        <input type="url" id="img-${item.id}" value="${item.image}" class="admin-modal-input">
                    </div>
                    <div class="mb-3">
                        <h5 class="text-md font-semibold text-slate-700 mb-2">Tallas y Stock:</h5>
                        <div id="tallas-editor-${item.id}" class="space-y-2">
                            ${item.tallas.map((talla, tallaIndex) => `
                                <div class="admin-talla-item" data-talla-index="${tallaIndex}">
                                    <input type="text" value="${talla.size}" placeholder="Talla (ej. S, M, 4)" class="admin-modal-input w-1/3 talla-size-input">
                                    <input type="number" value="${talla.stock}" placeholder="Stock" min="0" class="admin-modal-input w-1/3 talla-stock-input">
                                    <button class="remove-talla-btn text-red-500 hover:text-red-700 p-1" data-item-id="${item.id}" data-talla-index="${tallaIndex}">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </div>
                            `).join('')}
                        </div>
                        <button class="add-talla-btn mt-2 text-sm btn-secondary px-3 py-1 rounded-md" data-item-id="${item.id}">+ Añadir Talla</button>
                    </div>
                    <button class="save-product-changes-btn btn-primary px-4 py-2 rounded-md text-sm mt-3" data-item-id="${item.id}" data-category-key="${categoryKey}" data-item-index="${itemIndex}">Guardar Cambios de este Producto</button>
                `;
                adminProductsEditor.appendChild(productCard);
            });

            document.querySelectorAll('.add-talla-btn').forEach(btn => btn.addEventListener('click', handleAddTallaField));
            document.querySelectorAll('.remove-talla-btn').forEach(btn => btn.addEventListener('click', handleRemoveTallaField));
            document.querySelectorAll('.save-product-changes-btn').forEach(btn => btn.addEventListener('click', handleSaveProductChanges));
            document.querySelectorAll('.delete-product-btn').forEach(btn => btn.addEventListener('click', handleDeleteProductClick));
        }

        function handleAddTallaField(event) {
            const button = event.target.closest('.add-talla-btn');
            const itemId = button.dataset.itemId;
            const tallasEditorDiv = document.getElementById(`tallas-editor-${itemId}`);
            const newItemIndex = tallasEditorDiv.children.length;

            const newTallaDiv = document.createElement('div');
            newTallaDiv.className = 'admin-talla-item';
            newTallaDiv.dataset.tallaIndex = newItemIndex;
            newTallaDiv.innerHTML = `
                <input type="text" placeholder="Talla" class="admin-modal-input w-1/3 talla-size-input">
                <input type="number" placeholder="Stock" min="0" class="admin-modal-input w-1/3 talla-stock-input">
                <button class="remove-talla-btn text-red-500 hover:text-red-700 p-1" data-talla-index="0">
                                <i class="fas fa-trash-alt"></i>
                            </button>
            `;
            tallasEditorDiv.appendChild(newTallaDiv);
            newTallaDiv.querySelector('.remove-talla-btn').addEventListener('click', handleRemoveNewTallaField);
        }

        function handleRemoveTallaField(event) {
            const button = event.target.closest('.remove-talla-btn');
            button.parentElement.remove();
        }

        function handleSaveProductChanges(event) {
            const button = event.target.closest('.save-product-changes-btn');
            const itemId = button.dataset.itemId;
            const categoryKey = button.dataset.categoryKey;
            const itemIndex = parseInt(button.dataset.itemIndex);

            let productInMockData = mockPajamasData[categoryKey].items[itemIndex];

            if (!productInMockData || productInMockData.id !== itemId) {
                showAlert("Error: No se pudo encontrar el producto para actualizar.", "Error de Sincronización");
                return;
            }

            const originalProductData = JSON.parse(JSON.stringify(productInMockData));

            const nameInput = document.getElementById(`name-${itemId}`);
            let newName = productInMockData.name;
            if (nameInput && nameInput.value.trim() !== "") {
                newName = nameInput.value.trim();
                if (originalProductData.name !== newName) {
                    logAdminChange("MODIFICADO", originalProductData.name, itemId, "Nombre", originalProductData.name, newName, mockPajamasData[categoryKey].title);
                    productInMockData.name = newName;
                }
            } else {
                showAlert("El nombre del producto no puede estar vacío.", "Error de Validación");
                return;
            }

            const imageUrlInput = document.getElementById(`img-${itemId}`);
            if (imageUrlInput && originalProductData.image !== imageUrlInput.value.trim()) {
                logAdminChange("MODIFICADO", newName, itemId, "URL Imagen", originalProductData.image, imageUrlInput.value.trim(), mockPajamasData[categoryKey].title);
                productInMockData.image = imageUrlInput.value.trim();
            }


            const newTallas = [];
            const tallasEditorDiv = document.getElementById(`tallas-editor-${itemId}`);
            tallasEditorDiv.querySelectorAll('.admin-talla-item').forEach(tallaDiv => {
                const sizeInput = tallaDiv.querySelector('.talla-size-input');
                const stockInput = tallaDiv.querySelector('.talla-stock-input');
                if (sizeInput && stockInput && sizeInput.value.trim() !== "") {
                    newTallas.push({
                        size: sizeInput.value.trim(),
                        stock: parseInt(stockInput.value) || 0
                    });
                }
            });

            console.log("Collected newTallas in handleSaveProductChanges:", newTallas); // Debug log

            const oldTallasMap = new Map(originalProductData.tallas.map(t => [t.size, t.stock]));
            const newTallasMap = new Map(newTallas.map(t => [t.size, t.stock]));

            newTallas.forEach(nt => {
                if (!oldTallasMap.has(nt.size)) {
                    logAdminChange("MODIFICADO", newName, itemId, "Talla Añadida", "-", `${nt.size} (Stock: ${nt.stock})`, mockPajamasData[categoryKey].title);
                } else if (oldTallasMap.get(nt.size) !== nt.stock) {
                    logAdminChange("MODIFICADO", newName, itemId, `Stock Talla ${nt.size}`, oldTallasMap.get(nt.size), nt.stock, mockPajamasData[categoryKey].title);
                }
            });
            originalProductData.tallas.forEach(ot => {
                if (!newTallasMap.has(ot.size)) {
                    logAdminChange("MODIFICADO", newName, itemId, "Talla Eliminada", `${ot.size} (Stock: ${ot.stock})`, mockPajamasData[categoryKey].title);
                }
            });

            productInMockData.tallas = newTallas;

            mockPajamasData[categoryKey].items.sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)); // Re-sort after change

            showAlert(`Producto "${productInMockData.name}" actualizado.`, "Producto Guardado");
            renderAllProductSections();
            loadProductsForEditing(categoryKey);
        }

        function handleDeleteProductClick(event) {
            const button = event.target.closest('.delete-product-btn');
            const itemId = button.dataset.itemId;
            const categoryKey = button.dataset.categoryKey;
            const itemName = button.dataset.itemName; // Get item name directly from dataset

            showAlert(
                `¿Estás seguro de que deseas eliminar la pijama "${itemName}" (ID: ${itemId})? Esta acción no se puede deshacer.`,
                "Confirmar Eliminación",
                () => {
                    performDeleteProduct(categoryKey, itemId, itemName);
                }
            );
        }

        function performDeleteProduct(categoryKey, itemId, itemName) {
            let targetCategoryTitle = mockPajamasData[categoryKey].title;
            // Filter to create a new array without the deleted item
            mockPajamasData[categoryKey].items = mockPajamasData[categoryKey].items.filter(item => item.id !== itemId);

            mockPajamasData[categoryKey].items.sort((a, b) => extractNumberFromName(a.name) - extractNumberFromName(b.name)); // Re-sort after deletion


            logAdminChange("ELIMINADO", itemName, itemId, "Pijama completa", `Producto eliminado (era de ${targetCategoryTitle})`, "-", targetCategoryTitle);
            showAlert(`Pijama "${itemName}" eliminada exitosamente.`, "Eliminación Exitosa");
            renderAllProductSections();
            loadProductsForEditing(categoryKey);
        }

        if (downloadChangesReportBtn) {
            downloadChangesReportBtn.addEventListener('click', generateChangesReportPDF);
        }

        function generateChangesReportPDF() {
            if (adminChangesLog.length === 0) {
                showAlert("No hay cambios para reportar en esta sesión.", "Reporte Vacío");
                return;
            }

            let reportHtml = `
                <div style="font-family: Arial, sans-serif; margin: 20px; padding: 20px; color: #333;">
                    <div style="text-align: center; margin-bottom: 30px;">
                           <img src="https://textilesmay.shop/wp-content/uploads/2025/03/cropped-cropped-log-1.png" alt="Logo Textiles May" style="max-height: 80px; margin-bottom: 15px;">
                        <h1 style="color: #D1306C; font-size: 30px; margin:0; font-weight: bold; text-transform: uppercase;">Reporte de Cambios Administrativos</h1>
                        <p style="font-size: 14px; color: #666; margin-top: 5px;">Generado el: ${new Date().toLocaleString('es-CO')}</p>
                        <p style="font-size: 12px; color: #888; font-style: italic; margin-top: 10px;">Este reporte incluye los cambios realizados durante la sesión actual del navegador.</p>
                    </div>
                    <hr style="border: 0; height: 1px; background-color: #f0f0f0; margin: 20px 0;">
            `;

            const changesByType = {
                "AÑADIDO": [],
                "MODIFICADO": [],
                "ELIMINADO": []
            };

            adminChangesLog.forEach(log => {
                if (changesByType[log.type]) {
                    changesByType[log.type].push(log);
                }
            });

            for (const type in changesByType) {
                if (changesByType[type].length > 0) {
                    reportHtml += `<h2 style="color: #D1306C; font-size: 24px; border-bottom: 2px solid #FFD1DC; padding-bottom: 8px; margin-top: 40px; margin-bottom: 20px; font-weight: bold;">Pijamas ${type === 'AÑADIDO' ? 'Añadidas' : type === 'MODIFICADO' ? 'Modificadas' : 'Eliminadas'}</h2>`;

                    changesByType[type].forEach(log => {
                        reportHtml += `
                            <div style="margin-bottom: 20px; padding: 15px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #ffffff; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                                <p style="font-size: 16px; margin-bottom: 8px;"><strong>Pijama:</strong> ${log.productName} (ID: ${log.productId})</p>
                                <p style="font-size: 14px; margin-bottom: 8px;"><strong>Categoría:</strong> ${log.category}</p>`;

                        if (type === "AÑADIDO") {
                            reportHtml += `<p style="font-size: 14px; margin-bottom: 5px;"><strong>Detalles Añadidos:</strong></p>
                                <pre style="white-space: pre-wrap; word-wrap: break-word; background-color: #e6ffe6; padding: 10px; border-radius: 5px; border: 1px dashed #aaffaa; font-size: 13px;">${log.newValue}</pre>`;
                        } else if (type === "ELIMINADO") {
                            reportHtml += `<p style="font-size: 14px; margin-bottom: 5px;"><strong>Detalles Eliminados:</strong></p>
                                <pre style="white-space: pre-wrap; word-wrap: break-word; background-color: #ffe6e6; padding: 10px; border-radius: 5px; border: 1px dashed #ffaaaa; font-size: 13px;">${log.oldValue}</pre>`;
                        } else if (type === "MODIFICADO") {
                            reportHtml += `<p style="font-size: 14px; margin-bottom: 5px;"><strong>Cambios:</strong></p>
                                <ul style="list-style-type: none; padding-left: 0; margin-left: 0;">
                                    <li style="margin-bottom: 3px; font-size: 14px; display: flex; justify-content: space-between; align-items: baseline;">
                                        <span style="font-weight: bold; min-width: 100px;">${log.field}:</span>
                                        <span style="color: #cc0000; text-decoration: line-through; flex-grow: 1; text-align: left; margin-right: 10px;">${log.oldValue}</span>
                                        <span style="color: #008000; font-weight: bold; flex-grow: 1; text-align: right;">${log.newValue}</span>
                                    </li>
                                </ul>`;
                        }
                        reportHtml += `<p style="font-size:0.9em; color: #999; text-align: right; margin-top: 15px;"><i>Registrado: ${log.timestamp}</i></p>
                            </div>`;
                    });
                }
            }
            reportHtml += `<div style="text-align: center; margin-top: 50px; padding-top: 20px; border-top: 1px solid #f0f0f0;">
                                <p style="font-size: 16px; color: #D1306C; font-weight: bold;">¡Gracias por tu administración!</p>
                            </div>
                        </div>`;

            const element = document.createElement('div');
            element.innerHTML = reportHtml;
            document.body.appendChild(element);

            html2pdf().from(element).set({
                margin: [15, 10, 15, 10],
                filename: `Reporte_Cambios_TextilesMay_${new Date().toISOString().slice(0,10)}.pdf`,
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2, logging: false, useCORS: true, scrollY: 0 },
                jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
            }).save().then(() => {
                document.body.removeChild(element);
            }).catch(err => {
                showAlert("Error al generar el reporte PDF. Por favor, asegúrate de que no haya elementos de imagen rotos en los datos o inténtalo de nuevo.", "Error en PDF");
                console.error("Error PDF Report:", err);
                if(document.body.contains(element)) { // Ensure element is still in DOM before trying to remove
                     document.body.removeChild(element);
                }
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            renderAllProductSections();
            updateCartDisplay();

            const cartModalEl = document.getElementById('cart-modal');
            const openCartModalBtn = document.getElementById('open-cart-modal');
            const closeCartModalBtn = document.getElementById('close-cart-modal');
            const printOrderBtn = document.getElementById('print-order-btn');
            const whatsappOrderBtn = document.getElementById('whatsapp-order-btn');
            const cartItemsDisplay = document.getElementById('cart-items-display');

            if (openCartModalBtn && cartModalEl) openCartModalBtn.addEventListener('click', () => { renderCartModal(); cartModalEl.classList.remove('hidden'); });
            if (closeCartModalBtn && cartModalEl) closeCartModalBtn.addEventListener('click', () => cartModalEl.classList.add('hidden'));
            if (cartModalEl) cartModalEl.addEventListener('click', (e) => { if (e.target === cartModalEl) cartModalEl.classList.add('hidden'); });

            if (cartItemsDisplay) {
                cartItemsDisplay.addEventListener('click', (event) => {
                    const target = event.target.closest('.cart-qty-btn, .remove-from-cart-btn');
                    if (!target) return;
                    const productId = target.dataset.productId;
                    const selectedSize = target.dataset.size;
                    if (target.classList.contains('cart-qty-btn')) {
                        const action = target.dataset.action;
                        const currentItem = cartItems.find(item => item.productId === productId && item.selectedSize === selectedSize);
                        if (!currentItem) return;
                        let newQuantity = currentItem.selectedQuantity;
                        if (action === 'increase') newQuantity++; else if (action === 'decrease') newQuantity--;
                        updateCartItemQuantity(productId, selectedSize, newQuantity);
                    } else if (target.classList.contains('remove-from-cart-btn')) {
                        removeCartItem(productId, selectedSize);
                    }
                });
            }

            if (printOrderBtn) {
                printOrderBtn.addEventListener('click', () => {
                    const customerName = document.getElementById('customer-name').value.trim();
                    const customerAddress = document.getElementById('customer-address').value.trim();
                    const customerCity = document.getElementById('customer-city').value.trim();
                    const customerEmail = document.getElementById('customer-email').value.trim();

                    if (cartItems.length === 0) { showAlert("Tu carrito está vacío. Añade productos antes de generar el pedido."); return; }
                    if (!customerName || !customerAddress || !customerCity) { showAlert("Por favor, completa tu nombre, dirección y ciudad para el pedido."); return; }

                    let orderHtmlContent = `
                        <div style="font-family: Arial, sans-serif; margin: 20px; padding: 20px; color: #333;">
                            <div style="text-align: center; margin-bottom: 30px;">
                                <img src="https://textilesmay.shop/wp-content/uploads/2025/03/cropped-cropped-log-1.png" alt="Logo Textiles May" style="max-height: 70px; margin-bottom: 10px;">
                                <h1 style="color: #D1306C; font-size: 24px; margin:0; font-weight: bold; text-transform: uppercase;">Resumen de Pedido - Textiles May</h1>
                                <p style="font-size: 12px; color: #666; margin-top: 5px;">Generado el: ${new Date().toLocaleString('es-CO')}</p>
                            </div>
                            <h2 style="color: #D1306C; font-size: 18px; border-bottom: 2px solid #FFD1DC; padding-bottom: 5px; margin-bottom: 15px; font-weight: bold;">Datos del Cliente:</h2>
                            <p style="margin-bottom: 5px;"><strong style="color: #555;">Nombre:</strong> ${customerName}</p>
                            <p style="margin-bottom: 5px;"><strong style="color: #555;">Dirección:</strong> ${customerAddress}</p>
                            <p style="margin-bottom: 5px;"><strong style="color: #555;">Ciudad:</strong> ${customerCity}</p>
                            ${customerEmail ? `<p style="margin-bottom: 5px;"><strong style="color: #555;">Correo:</strong> ${customerEmail}</p>` : ''}
                            <h2 style="color: #D1306C; font-size: 18px; border-bottom: 2px solid #FFD1DC; padding-bottom: 5px; margin-top: 30px; margin-bottom: 15px; font-weight: bold;">Productos Seleccionados:</h2>
                            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                                <thead>
                                    <tr style="background-color: #FFD1DC;">
                                        <th style="padding: 10px; border: 1px solid #ddd; text-align: left; color: #D1306C;">Producto</th>
                                        <th style="padding: 10px; border: 1px solid #ddd; text-align: left; color: #D1306C;">Talla</th>
                                        <th style="padding: 10px; border: 1px solid #ddd; text-align: right; color: #D1306C;">Cantidad</th>
                                    </tr>
                                </thead>
                                <tbody>`;
                    cartItems.forEach(item => {
                        orderHtmlContent += `<tr>
                                                <td style="padding: 8px; border: 1px solid #ddd;">${item.name}</td>
                                                <td style="padding: 8px; border: 1px solid #ddd;">${item.selectedSize}</td>
                                                <td style="padding: 8px; border: 1px solid #ddd; text-align: right;">${item.selectedQuantity}</td>
                                              </tr>`;
                    });
                    orderHtmlContent += `</tbody></table><p style="text-align: center; margin-top: 30px; font-size: 14px; color: #555;">¡Gracias por tu pedido!</p></div>`;

                    const element = document.createElement('div');
                    element.innerHTML = orderHtmlContent;
                    document.body.appendChild(element);
                    html2pdf().from(element).set({ margin: [10,10,10,10], filename: `Pedido_TextilesMay_${customerName.replace(/\s+/g, '_')||'Cliente'}.pdf`, image: {type:'jpeg', quality:0.98}, html2canvas:{scale:2, logging:false, useCORS:true}, jsPDF:{unit:'mm', format:'a4', orientation:'portrait'}}).save().then(()=>document.body.removeChild(element)).catch(err=>{showAlert("Error al generar PDF.");document.body.removeChild(element);});
                });
            }


            if (whatsappOrderBtn) {
                whatsappOrderBtn.addEventListener('click', () => {
                    const customerName = document.getElementById('customer-name').value.trim();
                    const customerAddress = document.getElementById('customer-address').value.trim();
                    const customerCity = document.getElementById('customer-city').value.trim();
                    if (cartItems.length === 0) { showAlert("Tu carrito está vacío."); return; }
                    if (!customerName) { showAlert("Ingresa tu nombre para WhatsApp."); return; }
                    let orderMessage = `*¡Nuevo Pedido de Textiles May!* 🎉\n\n*Cliente:* ${customerName}\n`;
                    if (customerAddress) orderMessage += `*Dirección:* ${customerAddress}\n`;
                    if (customerCity) orderMessage += `*Ciudad:* ${customerCity}\n`;
                    orderMessage += `\n*Detalle del Pedido:*\n`;
                    cartItems.forEach(item => { orderMessage += `------------------------------------\n*Producto:* ${item.name}\n*Talla:* ${item.selectedSize}\n*Cantidad:* ${item.selectedQuantity} unidad(es)\n`; });
                    orderMessage += `------------------------------------\n\n¡Quedo atento/a a la confirmación! 😊`;
                    const businessWhatsAppNumber = "";
                    window.open(`https://wa.me/${businessWhatsAppNumber}?text=${encodeURIComponent(orderMessage)}`, '_blank');
                });
            }

            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileMenu = document.getElementById('mobile-menu');
            if (mobileMenuButton && mobileMenu) mobileMenuButton.addEventListener('click', () => mobileMenu.classList.toggle('hidden'));

            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    const targetId = this.getAttribute('href');
                    if (targetId && targetId.length > 1) {
                        const targetElement = document.querySelector(targetId);
                        if (targetElement) {
                            const headerOffset = document.querySelector('header.sticky')?.offsetHeight || 0;
                            const elementPosition = targetElement.getBoundingClientRect().top;
                            const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                            window.scrollTo({ top: offsetPosition, behavior: "smooth" });
                        }
                    }
                    if (mobileMenu && !mobileMenu.classList.contains('hidden')) mobileMenu.classList.add('hidden');
                });
            });

            // Offer button and modal logic
            const offerButton = document.getElementById('offer-button');
            const offerModal = document.getElementById('offer-modal');
            const offerModalCloseBtn = document.getElementById('offer-modal-close-btn');

            if (offerButton && offerModal && offerModalCloseBtn) {
                // Abre el modal al hacer clic en el botón de oferta
                offerButton.addEventListener('click', () => {
                    offerModal.classList.remove('hidden');
                    offerModal.classList.add('show');
                });

                // Cierra el modal al hacer clic en el botón de cerrar
                offerModalCloseBtn.addEventListener('click', () => {
                    offerModal.classList.remove('show');
                    offerModal.classList.add('hidden');
                });

                // Cierra el modal al hacer clic fuera del contenido de la imagen
                offerModal.addEventListener('click', (e) => {
                    if (e.target === offerModal) {
                        offerModal.classList.remove('show');
                        offerModal.classList.add('hidden');
                    }
                });
            }
        });
    </script>
</body>
</html>