<?php /* Template Name: Criterio Digital Productos */ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notebooks Certificados | Criterio Digital</title>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/style.css">
    <style>
        .product-tag { background: #e2e8f0; color: #334155; font-size: 0.75rem; padding: 3px 12px; border-radius: 50px; font-weight: 600; }
        .badge-grado { position: absolute; top: 1rem; right: 1rem; background-color: var(--primary); color: white; font-size: 0.75rem; font-weight: 700; padding: 0.4rem 1rem; border-radius: 50px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); z-index: 10; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
        #cart-drawer.open { right: 0 !important; }
        #product-modal-backdrop.open { opacity: 1 !important; visibility: visible !important; }
        #product-modal-content.open { transform: translateY(0) scale(1) !important; opacity: 1 !important; }
        .btn-icon:hover { background-color: #f1f5f9 !important; border-color: #94a3b8 !important; }
        .btn-icon svg { transition: transform 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        .btn-icon:active svg { transform: scale(0.85); }
        
        /* Modal Scroll Customization */
        .modal-body-scroll::-webkit-scrollbar { width: 8px; }
        .modal-body-scroll::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 4px; }
        .modal-body-scroll::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .modal-body-scroll::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
        
        /* ESTILOS DEL CONFIGURADOR MODULAR COMPACTO */
        .cd-config-wrapper { font-family: inherit; margin: 16px 0; display: flex; flex-direction: column; gap: 16px; background: #f8fafc; border-radius: 12px; padding: 16px; border: 1px dashed #cbd5e1; }
        .cd-selector-group { display: flex; flex-direction: column; gap: 8px; }
        .cd-selector-title { font-size: 0.85rem; font-weight: 700; color: #1e293b; display: flex; align-items: center; gap: 6px; }
        .cd-options-flex { display: flex; flex-wrap: wrap; gap: 8px; }
        .cd-option-btn { border: 1.5px solid #e2e8f0; background-color: #ffffff; border-radius: 8px; padding: 8px 12px; cursor: pointer; display: flex; flex-direction: column; align-items: flex-start; min-width: 90px; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); position: relative; }
        .cd-option-btn:hover:not(.disabled) { border-color: #94a3b8; background-color: #f8fafc; }
        .cd-option-btn.selected { border-color: #1d4ed8; background-color: #eff6ff; box-shadow: 0 2px 4px rgba(29, 78, 216, 0.1); }
        .cd-option-btn.disabled { opacity: 0.4; cursor: not-allowed; background-color: #f1f5f9; border-color: #cbd5e1; }
        .cd-opt-name { font-size: 0.85rem; font-weight: 700; color: #0f172a; line-height: 1.2; }
        .cd-opt-price { font-size: 0.70rem; font-weight: 500; color: #64748b; margin-top: 2px; }
        .cd-opt-price.highlight { color: #1d4ed8; font-weight: 600; }
        .cd-opt-price.out { color: #ef4444; }
        .cd-skeleton-box { width: 90px; height: 44px; border-radius: 8px; background: linear-gradient(90deg, #f1f5f9 25%, #e2e8f0 50%, #f1f5f9 75%); background-size: 200% 100%; animation: skel 1.5s infinite; }
        @keyframes skel { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
        .cd-ver-mas-link { display: inline-flex; align-items: center; justify-content: center; color: #1d4ed8; font-size: 0.85rem; font-weight: 700; text-decoration: none; cursor: pointer; padding: 12px; border-radius: 12px; border: 1px solid #bfdbfe; background-color: #eff6ff; transition: all 0.2s ease; width: 100%; box-sizing: border-box; }
        .cd-ver-mas-link:hover { color: #1e3a8a; background-color: #dbeafe; border-color: #93c5fd; }
    </style>
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <!-- Navbar -->
    <header class="navbar">
        <div class="container nav-content">
            <a href="#" class="logo-container">
                <img src="<?php echo get_stylesheet_directory_uri(); ?>/LogoPNG.png" alt="Criterio Digital Logo" class="logo">
            </a>
            <nav class="nav-links">
                <a href="#inicio">Inicio</a>
                <a href="#nosotros">Por Qué Elegirnos</a>
                <a href="#servicios">Garantías</a>
                <a href="#productos">Catálogo</a>
                <a href="#contacto" class="btn-primary nav-contact-btn">Asesoría</a>
            </nav>
        </div>
    </header>

    <!-- PRODUCT MODAL (QUICK VIEW) -->
    <div id="product-modal-backdrop" onclick="if(event.target === this) window.closeProductModal()" style="position:fixed; top:0; left:0; width:100%; height:100vh; background:rgba(15, 23, 42, 0.85); backdrop-filter:blur(5px); z-index:9999; display:flex; align-items:center; justify-content:center; opacity:0; visibility:hidden; transition:all 0.3s ease-out; padding:20px;">
        <div id="product-modal-content" style="background:white; width:100%; max-width:900px; max-height:90vh; border-radius:24px; box-shadow:0 25px 50px -12px rgba(0,0,0,0.5); overflow:hidden; display:flex; flex-direction:column; transform:translateY(30px) scale(0.95); opacity:0; transition:all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); position:relative;">
            
            <!-- Close Button -->
            <button onclick="window.closeProductModal()" style="position:absolute; top:20px; right:20px; background:white; border:1px solid #e2e8f0; border-radius:50%; width:44px; height:44px; display:flex; align-items:center; justify-content:center; cursor:pointer; box-shadow:0 4px 6px rgba(0,0,0,0.05); z-index:10; color:#475569; transition:all 0.2s;" onmouseover="this.style.background='#f1f5f9'; this.style.color='#0f172a'" onmouseout="this.style.background='white'; this.style.color='#475569'">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
            
            <!-- Dynamic Content Body -->
            <div id="product-modal-body" class="modal-body-scroll" style="display:flex; flex-wrap:wrap; overflow-y:auto; flex-grow:1; max-height:calc(90vh); background:white;">
                <!-- Content injected via JS -->
            </div>
        </div>
    </div>

    <!-- CART FLOATING BUTTON -->
    <div onclick="window.toggleCart()" style="position:fixed; bottom:30px; right:30px; background:var(--primary); color:white; width:60px; height:60px; border-radius:50%; display:flex; align-items:center; justify-content:center; cursor:pointer; box-shadow:0 10px 25px rgba(0,0,0,0.2); z-index:998; transition:transform 0.3s;">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
        <span id="cart-count" style="position:absolute; top:-5px; right:-5px; background:#ef4444; color:white; font-size:0.8rem; font-weight:bold; width:24px; height:24px; border-radius:50%; display:none; align-items:center; justify-content:center; border:2px solid white; box-shadow:0 2px 5px rgba(0,0,0,0.2);">0</span>
    </div>

    <!-- CART DRAWER -->
    <div id="cart-drawer" style="position:fixed; top:0; right:-400px; width:100%; max-width:400px; height:100vh; background:white; box-shadow:-5px 0 25px rgba(0,0,0,0.1); z-index:999; transition:right 0.3s cubic-bezier(0.4, 0, 0.2, 1); display:flex; flex-direction:column;">
        <div style="padding:20px; border-bottom:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; background:#f8fafc;">
            <h3 style="margin:0; font-size:1.4rem; color:#0f172a; display:flex; align-items:center; gap:10px;">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
                Tu Carrito
            </h3>
            <button onclick="window.toggleCart()" style="background:none; border:none; cursor:pointer; color:#64748b; padding:5px;">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div id="cart-items" style="flex-grow:1; overflow-y:auto; padding:20px;">
            <p style="text-align:center; color:#94a3b8; padding: 2rem 0;">Tu carrito está vacío</p>
        </div>
        <div style="padding:20px; border-top:1px solid #e2e8f0; background:#f8fafc;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
                <span style="font-weight:600; color:#475569;">Total estimado:</span>
                <span id="cart-total" style="font-size:1.5rem; font-weight:800; color:#0f172a;">$0</span>
            </div>
            <button onclick="window.checkoutCart()" class="btn-primary" style="width:100%; border-radius:12px; padding:15px; font-size:1.1rem; display:flex; justify-content:center; align-items:center; gap:10px;">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg>
                Comprar todo vía WhatsApp
            </button>
        </div>
    </div>

    <!-- SECCIÓN ELIMINADA: EL DRAWER LATERAL FUE DESCARTADO POR EL MODAL CENTRAL -->

    <!-- Hero Section -->
    <section id="inicio" class="hero">
        <div class="container hero-content">
            <div class="hero-text animate-on-scroll">
                <span class="badge">Hardware Especializado</span>
                <h1>Equipos Computacionales de <span>Alto Rendimiento</span></h1>
                <p>Notebooks empresariales y gaming testeados bajo estándares internacionales. Potencia garantizada para llevar tu productividad o setup al siguiente nivel.</p>
                <div class="hero-buttons">
                    <a href="#productos" class="btn-secondary">Ver Catálogo</a>
                </div>
            </div>
            <div class="hero-image animate-on-scroll slide-left">
                <div class="image-wrapper glass-panel floating-element">
                    <div class="carousel-viewport">
                        <div class="carousel-track" id="hero-carousel">
                            <img src="https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=800&q=80" alt="Notebook Ejecutivo" class="carousel-img">
                            <img src="https://images.unsplash.com/photo-1603302576837-37561b2e2302?w=800&q=80" alt="Laptop Gaming" class="carousel-img">
                            <img src="https://images.unsplash.com/photo-1588872657578-7efd1f1555ed?w=800&q=80" alt="Workstation Profesional" class="carousel-img">
                        </div>
                    </div>
                </div>
            </div>
            <div class="hero-sidebar">
                <a href="#nosotros" class="btn-primary btn-floating-right">Por qué nosotros</a>
            </div>
        </div>
    </section>

    <!-- Quienes Somos Section -->
    <section id="nosotros" class="about">
        <div class="container about-content">
            <div class="about-text animate-on-scroll">
                <h2>Expertos en <span>Hardware Certificado</span></h2>
                <div class="divider"></div>
                <p class="lead">Equipos seminuevos con calidad de fábrica</p>
                <p>En <strong>Criterio Digital</strong> no solo vendemos notebooks, somos expertos apasionados por el rendimiento. Cada equipo que entra a nuestro inventario pasa por un proceso de revisión exhaustivo donde testeamos discos, memoria RAM, batería, pantallas y desgaste térmico.</p>
                <p>Entendemos que un notebook es tu herramienta principal. Por eso, nos aseguramos de que recibas una máquina potente, limpia y lista para usar desde el primer segundo de encendido, aliviando tu bolsillo frente a equipos nuevos.</p>
            </div>
            <div class="about-stats animate-on-scroll slide-left">
                <div class="stat-card">
                    <h3 class="counter">Grado A</h3>
                    <p>Condición Estética</p>
                </div>
                <div class="stat-card">
                    <h3 class="counter">100%</h3>
                    <p>Hardware Testeado</p>
                </div>
                <div class="stat-card">
                    <h3 class="counter">3 Meses</h3>
                    <p>De Garantía</p>
                </div>
            </div>
        </div>
    </section>

    <!-- Servicios Section -->
    <section id="servicios" class="services">
        <div class="container text-center animate-on-scroll">
            <h2>Nuestra <span>Promesa de Valor</span></h2>
            <p class="section-subtitle">Compra con la tranquilidad que mereces al invertir en tecnología</p>
            
            <div class="services-grid">
                <div class="service-card animate-on-scroll">
                    <div class="icon-container">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
                    </div>
                    <h3>Control de Calidad Riguroso</h3>
                    <p>Validamos el estrés del procesador, la vida útil de la unidad de estado sólido (SSD) y el desgaste de la batería para asegurar el máximo rendimiento de forma transparente.</p>
                </div>
                
                <div class="service-card animate-on-scroll" style="transition-delay: 0.1s;">
                    <div class="icon-container">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="3" width="15" height="13"></rect><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon><circle cx="5.5" cy="18.5" r="2.5"></circle><circle cx="18.5" cy="18.5" r="2.5"></circle></svg>
                    </div>
                    <h3>Despacho Rápido y Seguro</h3>
                    <p>Enviamos tu producto a cualquier región en un embalaje súper reforzado anti-golpes, para que te llegue rápido e impecable directo a la puerta de tu casa u oficina.</p>
                </div>
                
                <div class="service-card animate-on-scroll" style="transition-delay: 0.2s;">
                    <div class="icon-container">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
                    </div>
                    <h3>Soporte Técnico Directo</h3>
                    <p>Cuentas con garantía íntegra respaldada por Criterio Digital. Si tienes alguna configuración técnica o problema con tu equipo, estamos a un mensaje táctico de WhatsApp de distancia.</p>
                </div>
            </div>
        </div>
    </section>

    <!-- Grilla de Productos Dinámica -->
    <section id="productos" class="products" style="padding-top: 100px; padding-bottom: 100px; background-color: var(--bg-secondary);">
        <div class="container text-center animate-on-scroll">
            <h2>Nuestro <span>Catálogo en Stock</span></h2>
            <p class="section-subtitle" style="margin-bottom: 3rem;">Selecciona tu próximo equipo y comunícate con un asesor para reservar el tuyo antes que se agote.</p>
            <div id="products-grid" class="products-grid"></div>
        </div>
    </section>

    <!-- SCRIPT AJAX PARA RECUPERAR STOCK Y MOTOR DE CARRITO DE COMPRAS -->
    <script>
    // --- LÓGICA DE MEMORIA GLOBAL Y MODAL ---
    window.catalogDb = [];
    
    window.openProductModal = function(id) {
        const p = window.catalogDb.find(item => item.productId === id);
        if(!p) return;
        
        const backdrop = document.getElementById('product-modal-backdrop');
        const content = document.getElementById('product-modal-content');
        const body = document.getElementById('product-modal-body');
        
        const fmtr = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP", maximumFractionDigits: 0 });
        const finalP = p.offerPrice ? p.offerPrice : p.price;
        const oldP = p.offerPrice ? `<span style="text-decoration:line-through;color:#94a3b8;font-size:1.1rem;margin-right:15px;font-weight:normal;">${fmtr.format(p.price)}</span>` : "";
        
        let img = "https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=500&q=80";
        if (p.images && p.images[0] && !p.images[0].includes(".../")) img = p.images[0];
        else if (p?.specs?.deviceType === "PC Gamer") img = "https://images.unsplash.com/photo-1603302576837-37561b2e2302?w=500&q=80";
        
        // Insignias en Modal
        let badgeHtml = '';
        if (p?.condition?.cosmeticState && p.condition.cosmeticState.trim() !== '') {
            badgeHtml = `<div style="position:absolute; top:20px; left:20px; background:var(--primary); color:white; font-size:0.8rem; font-weight:700; padding:6px 14px; border-radius:50px; box-shadow:0 4px 6px rgba(0,0,0,0.1); z-index:5;">${p.condition.cosmeticState}</div>`;
        }
        
        const ramDetails = p.specs?.ram?.details?.[0] || '';
        const storageDetails = p.specs?.storage?.details?.[0] || '';
        
        const brandIcon = p.brand.toLowerCase().includes('lenovo') ? 'L' : (p.brand.toLowerCase().includes('hp') ? 'H' : '💻');
        
        body.innerHTML = `
            <div style="flex: 1 1 350px; background:#f8fafc; display:flex; align-items:center; justify-content:center; position:relative; min-height:300px;">
                ${badgeHtml}
                <img src="${img}" style="width:100%; height:100%; object-fit:cover; position:absolute; inset:0;">
                <div style="position:absolute; inset:0; background:linear-gradient(to top, rgba(15,23,42,0.6) 0%, transparent 40%);"></div>
                <div style="position:absolute; bottom:20px; left:20px; right:20px; display:flex; align-items:flex-end; justify-content:space-between;">
                    <span style="background:rgba(255,255,255,0.9); backdrop-filter:blur(4px); padding:4px 12px; border-radius:20px; font-weight:700; color:#0f172a; font-size:0.8rem; letter-spacing:1px; text-transform:uppercase;">${p.brand}</span>
                    <span style="color:white; font-size:0.8rem; text-shadow:0 2px 4px rgba(0,0,0,0.5);">SKU: ${p.productId}</span>
                </div>
            </div>
            
            <div style="flex: 1 1 450px; padding:40px; text-align:left; display:flex; flex-direction:column; background:white;">
                <h2 style="font-size: 2.2rem; margin-bottom: 0.5rem; color:#0f172a; line-height:1.1; font-weight:800;">${p.model}</h2>
                <div style="margin-bottom: 2rem; display:flex; align-items:center;">
                    ${oldP}
                    <span style="font-size:2.5rem; color:var(--primary); font-weight:800;">${fmtr.format(finalP)}</span>
                </div>
                
                <h4 style="font-size:0.9rem; color:#64748b; text-transform:uppercase; letter-spacing:1.5px; border-bottom:2px solid #f1f5f9; padding-bottom:10px; margin-bottom:1.5rem; font-weight:700;">Ficha Técnica Completa</h4>
                
                <ul style="list-style:none; padding:0; margin:0 0 2.5rem 0; color:#334155; font-size:1.05rem; display:flex; flex-direction:column; gap:16px;">
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">⚡</span> 
                        <div><strong style="color:#0f172a;">Procesador:</strong> <span style="color:#475569;">${p?.specs?.processor?.brand || ''} ${p?.specs?.processor?.generation || ''}</span></div>
                    </li>
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">🧠</span> 
                        <div><strong style="color:#0f172a;">Memoria RAM:</strong> <span style="color:#475569;">${p?.specs?.ram?.totalCapacity || ''} ${p?.specs?.ram?.type || ''}</span> <div style="color:#94a3b8; font-size:0.85rem; margin-top:2px;">${ramDetails}</div></div>
                    </li>
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">💾</span> 
                        <div><strong style="color:#0f172a;">Almacenamiento:</strong> <span style="color:#475569;">${p?.specs?.storage?.totalCapacity || ''}</span> <div style="color:#94a3b8; font-size:0.85rem; margin-top:2px;">${storageDetails}</div></div>
                    </li>
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">📺</span> 
                        <div><strong style="color:#0f172a;">Pantalla:</strong> <span style="color:#475569;">${p?.specs?.screen || ''}"</span></div>
                    </li>
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">🎮</span> 
                        <div><strong style="color:#0f172a;">Gráficos (GPU):</strong> <span style="color:#475569;">${p?.specs?.gpu?.brand || ''} ${p?.specs?.gpu?.vram ? '('+p?.specs?.gpu?.vram+')' : ''}</span></div>
                    </li>
                    <li style="display:flex; gap:12px; align-items:flex-start;">
                        <span style="color:var(--primary); font-size:1.2rem;">🔋</span> 
                        <div><strong style="color:#0f172a;">Salud de Batería:</strong> <span style="color:#475569;">${p?.condition?.batteryStatus || 'Óptima'}</span></div>
                    </li>
                </ul>
                
                <div style="margin-top:auto; display:flex; gap:15px; flex-direction:column;">
                    
                    <!-- CONFIGURADOR MODULAR INCORPORADO AL MODAL -->
                    <div class="cd-config-wrapper">
                        <div class="cd-selector-group">
                            <div class="cd-selector-title">🧠 Memoria RAM:</div>
                            <div class="cd-options-flex" id="modalRamOptions">
                                <div class="cd-skeleton-box"></div><div class="cd-skeleton-box"></div>
                            </div>
                        </div>
                        <div class="cd-selector-group" style="margin-top:6px;">
                            <div class="cd-selector-title">💾 Almacenamiento:</div>
                            <div class="cd-options-flex" id="modalSsdOptions">
                                <div class="cd-skeleton-box"></div><div class="cd-skeleton-box"></div><div class="cd-skeleton-box"></div>
                            </div>
                        </div>
                        <div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid #e2e8f0; padding-top:12px; margin-top:4px;">
                            <span style="font-size:0.9rem; color:#64748b; font-weight:600;">Subtotal Equipo:</span>
                            <span id="precio-modal" data-base="${finalP}" style="font-size:1.4rem; color:#0f172a; font-weight:800;">${fmtr.format(finalP)}</span>
                        </div>
                    </div>
                
                    <a href="https://wa.me/56994919000?text=Hola,%20quiero%20comprar%20ahora%20el%20notebook%20${p.brand}%20${p.model}%20(ID:%20${p.productId}).%20%C2%BFSigue%20en%20stock?" target="_blank" class="btn-primary" style="text-align:center; padding:16px; font-size:1.1rem; border-radius:12px; display:flex; justify-content:center; gap:10px; align-items:center; font-weight:700;" onclick="window.closeProductModal()">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg> Comprar Inmediatamente por WhatsApp
                    </a>
                </div>
            </div>
        `;
        
        backdrop.classList.add('open');
        content.classList.add('open');
        document.body.style.overflow = 'hidden'; // Hide main scroll
        
        // Disparador de API del configurador compacto
        window.dispararCargaDeVariaciones(p.productId);
    };
    
    window.closeProductModal = function() {
        const backdrop = document.getElementById('product-modal-backdrop');
        const content = document.getElementById('product-modal-content');
        if(!backdrop) return;
        
        content.classList.remove('open');
        backdrop.classList.remove('open');
        setTimeout(() => { document.body.style.overflow = ''; }, 300);
    };

    // --- LÓGICA DE CARRITO ---
    window.cartState = [];
    
    window.toggleCart = function() {
        document.getElementById('cart-drawer').classList.toggle('open');
    };
    
    window.addToCart = function(id, name, price, img) {
        const item = window.cartState.find(i => i.id === id);
        if (item) item.qty++;
        else window.cartState.push({ id, name, price, img, qty: 1 });
        window.renderCart();
        
        // Animación visual del botón (Feedback)
        const btn = document.getElementById('btn-cart-' + id);
        if(btn) {
            const oldHtml = btn.innerHTML;
            btn.innerHTML = `<svg width="22" height="22" color="#10b981" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
            setTimeout(() => { btn.innerHTML = oldHtml; }, 1000);
        }
    };
    
    window.removeFromCart = function(id) {
        window.cartState = window.cartState.filter(i => i.id !== id);
        window.renderCart();
    };
    
    window.renderCart = function() {
        const fmtr = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP", maximumFractionDigits: 0 });
        const countEl = document.getElementById('cart-count');
        const itemsEl = document.getElementById('cart-items');
        const totalEl = document.getElementById('cart-total');
        
        const totalQty = window.cartState.reduce((sum, i) => sum + i.qty, 0);
        countEl.textContent = totalQty;
        countEl.style.display = totalQty > 0 ? 'flex' : 'none';
        
        if (window.cartState.length === 0) {
            itemsEl.innerHTML = '<p style="text-align:center; color:#94a3b8; padding: 2rem 0;">Tu carrito está vacío</p>';
            totalEl.textContent = '$0';
            return;
        }
        
        let html = '';
        let totalSum = 0;
        window.cartState.forEach(i => {
            totalSum += i.price * i.qty;
            html += `
                <div style="display:flex; align-items:center; gap:12px; margin-bottom:1rem; padding-bottom:1rem; border-bottom:1px solid #f1f5f9;">
                    <img src="${i.img}" style="width:60px; height:60px; object-fit:cover; border-radius:10px; border:1px solid #e2e8f0;">
                    <div style="flex-grow:1;">
                        <div style="font-size:0.95rem; font-weight:700; color:#0f172a; line-height:1.2; margin-bottom:4px;">${i.name}</div>
                        <div style="font-size:0.85rem; color:#64748b;">Cant: ${i.qty} x <span style="color:var(--primary); font-weight:600;">${fmtr.format(i.price)}</span></div>
                    </div>
                    <button onclick="window.removeFromCart('${i.id}')" style="background:none; border:none; color:#ef4444; cursor:pointer; padding:5px; transition:transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'" title="Eliminar">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                    </button>
                </div>
            `;
        });
        itemsEl.innerHTML = html;
        totalEl.textContent = fmtr.format(totalSum);
    };

    window.checkoutCart = function() {
        if(window.cartState.length === 0) return;
        const fmtr = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP", maximumFractionDigits: 0 });
        const totalSum = window.cartState.reduce((sum, i) => sum + (i.price * i.qty), 0);
        let msg = "💳 *Hola Criterio Digital*, quiero concretar la compra de mi carrito con los siguientes equipos:\n\n";
        window.cartState.forEach(i => {
            msg += `🛒 ${i.qty}x ${i.name} (ID: ${i.id})\n     Subtotal: ${fmtr.format(i.price * i.qty)}\n`;
        });
        msg += `\n💰 *TOTAL A PAGAR: ${fmtr.format(totalSum)}*\n\n¿Por favor enviarme los datos de pago y confirmar stock?`;
        
        window.open('https://wa.me/56994919000?text=' + encodeURIComponent(msg), '_blank');
    };

    // --- LÓGICA DE FETCH INVENTARIO ---
    (function() {
        const container = document.getElementById("products-grid");
        if (!container) return;

        // Mostrar estado de carga
        container.innerHTML = `
            <div style="grid-column: 1/-1; padding: 4rem 2rem; background: white; border-radius: 24px; box-shadow: 0 10px 30px -10px rgba(0,0,0,0.05); text-align: center;">
                <svg style="animation: spin 1s linear infinite; width: 50px; height: 50px; color: var(--primary); margin: 0 auto 1.5rem;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="#cbd5e1" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <h3 style="font-size: 1.5rem; color: #334155; margin-bottom: 0.5rem;">Sincronizando Inventario</h3>
                <p style="color: #64748b;">Conectando con la bodega de Criterio Digital en tiempo real...</p>
            </div>
        `;

        fetch('https://us-central1-logistica-criterio.cloudfunctions.net/apiStock')
            .then(response => {
                if (!response.ok) throw new Error("Error HTTP: " + response.status);
                return response.json();
            })
            .then(res => {
                const data = res.data || [];
                window.catalogDb = data; // Almacenado Global para el Modal Rápido
                
                // Si la API no retorna equipos en stock
                if (data.length === 0) {
                    container.innerHTML = `
                        <div style="grid-column: 1/-1; padding: 4rem 2rem; background: white; border-radius: 24px; border: 2px dashed #cbd5e1; text-align: center;">
                            <svg style="width: 60px; height: 60px; color: #94a3b8; margin: 0 auto 1.5rem;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="8" y1="12" x2="16" y2="12"></line></svg>
                            <h3 style="font-size: 1.8rem; margin-bottom: 1rem; color: #0f172a;">Catálogo Temporalmente Agotado</h3>
                            <p style="font-size: 1.1rem; color: #64748b; max-width: 600px; margin: 0 auto 2rem;">Acabamos de vender los últimos equipos en stock de alta gama. Escríbenos para avisarte o reservarte prioridad cuando entre el próximo cargamento.</p>
                            <a href="https://wa.me/56994919000" target="_blank" class="btn-primary" style="display: inline-block;">Preguntar por Próximo Stock</a>
                        </div>
                    `;
                    return;
                }
                
                // Limpiar cargador
                container.innerHTML = "";
                
                // Renderizar Tarjetas
                data.forEach((p) => {
                    try {
                        const fmtr = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP", maximumFractionDigits: 0 });
                        const finalP = p.offerPrice ? p.offerPrice : p.price;
                        const oldP = p.offerPrice ? `<span style="text-decoration:line-through;color:#94a3b8;font-size:1.1rem;margin-right:15px;font-weight:normal;">${fmtr.format(p.price)}</span>` : "";
                        
                        let img = "https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=500&q=80";
                        if (p.images && p.images[0] && !p.images[0].includes(".../")) img = p.images[0];
                        else if (p?.specs?.deviceType === "PC Gamer") img = "https://images.unsplash.com/photo-1603302576837-37561b2e2302?w=500&q=80";

                        let tags = (p.tags || []).map(t => `<span class="product-tag">${t}</span>`).join("");
                        
                        const card = document.createElement("div");
                        card.className = "product-card is-visible";
                        card.style.animation = "none"; card.style.opacity = "1"; card.style.transform = "none";
                        card.style.position = "relative";
                        card.style.textAlign = "left";
                        
                        let ramDetails = p.specs?.ram?.details?.[0] || '';
                        let storageDetails = p.specs?.storage?.details?.[0] || '';
                        
                        // Badge Lógica Preventiva Vacío
                        let badgeHtml = '';
                        if (p?.condition?.cosmeticState && p.condition.cosmeticState.trim() !== '') {
                            badgeHtml = `<div class="badge-grado">${p.condition.cosmeticState}</div>`;
                        }
                        
                        card.innerHTML = `
                            <div class="product-image">
                                <img src="${img}" alt="${p.brand} ${p.model}">
                                ${badgeHtml}
                            </div>
                            <div class="product-info">
                                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 0.5rem;">
                                    <span style="font-size: 0.85rem; color: var(--primary); font-weight: 800; letter-spacing:1px; text-transform:uppercase;">${p.brand}</span>
                                    <span style="font-size: 0.75rem; color: #64748b; background:#f1f5f9; padding:2px 8px; border-radius:12px; border:1px solid #cbd5e1;">SKU: ${p.productId}</span>
                                </div>
                                <h3 style="font-size: 1.4rem; margin-bottom: 1rem; color:#0f172a; line-height:1.2; text-overflow:ellipsis; overflow:hidden; white-space:nowrap;" title="${p.model}">${p.model}</h3>
                                <div class="tags-container" style="margin-bottom: 1rem; display:flex; gap:0.5rem; flex-wrap:wrap;">${tags}</div>
                                
                                <div class="product-specs" style="font-size: 0.95rem; color: #475569; margin-bottom: 1.5rem; flex-grow: 1; background:#f8fafc; padding:1.2rem; border-radius:12px; border:1px solid #e2e8f0;">
                                    <div style="margin-bottom:0.7rem; display:flex; align-items:flex-start;">
                                        <span style="margin-right:8px;">💻</span> 
                                        <div><strong>${p?.specs?.processor?.brand || ''} ${p?.specs?.processor?.generation || ''}</strong></div>
                                    </div>
                                    <div style="margin-bottom:0.7rem; display:flex; align-items:flex-start;">
                                        <span style="margin-right:8px;">⚡</span> 
                                        <div>
                                            <strong>${p?.specs?.ram?.totalCapacity || ''} ${p?.specs?.ram?.type || ''}</strong>
                                            <div style="font-size:0.8rem; color:#94a3b8;">(${ramDetails})</div>
                                        </div>
                                    </div>
                                    <div style="margin-bottom:0.7rem; display:flex; align-items:flex-start;">
                                        <span style="margin-right:8px;">💾</span> 
                                        <div>
                                            <strong>${p?.specs?.storage?.totalCapacity || ''}</strong>
                                            <div style="font-size:0.8rem; color:#94a3b8;">${storageDetails}</div>
                                        </div>
                                    </div>
                                    <div style="display:flex; align-items:flex-start;">
                                        <span style="margin-right:8px;">📺</span> 
                                        <div>
                                            <strong>${p?.specs?.screen || ''}"</strong> — GPU: ${p?.specs?.gpu?.brand || ''}
                                            <div style="font-size:0.8rem; color:#94a3b8;">Batería: ${p?.condition?.batteryStatus || ''}</div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="product-price" style="display:flex; align-items:center; margin-bottom: 1rem;">
                                    ${oldP}
                                    <span style="font-size:1.8rem; color:var(--primary); font-weight:800;">${fmtr.format(finalP)}</span>
                                </div>
                                
                                <!-- PANEL MULTI-ACCION COMPACTO -->
                                <div style="display:flex; gap:8px; align-items:stretch; margin-top:0.5rem; flex-direction:column;">
                                    
                                    <button onclick="window.openProductModal('${p.productId}')" class="cd-ver-mas-link" title="Ver ficha técnica y cambiar RAM/SSD">
                                        Configurar Equipo y Ver Detalles
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-left:6px;"><path d="M5 12h14"></path><path d="M12 5l7 7-7 7"></path></svg>
                                    </button>
                                    
                                    <div style="display:flex; gap:8px;">
                                        <a href="https://www.mercadolibre.cl/checkout/product_id_v2=${p.productId}" class="btn-primary" style="flex-grow:1; text-align:center; border:none; border-radius:12px; font-weight:600; cursor:pointer; padding:12px 6px; font-size:1rem; display:flex; align-items:center; justify-content:center; background-color:#ffe600; color:#2d3277; text-decoration:none;">
                                            Comprar Ahora en M.L.
                                        </a>
                                        
                                        <a href="https://wa.me/56994919000?text=Hola,%20tengo%20una%20duda%20sobre%20el%20notebook%20${p.model}" target="_blank" class="btn-icon" style="background:#25D366; color:white; border:none; border-radius:12px; padding:0 14px; display:flex; align-items:center; justify-content:center; flex-shrink:0; text-decoration:none; box-shadow:0 4px 10px rgba(37,211,102,0.3);" title="Consultas rápidas en WhatsApp">
                                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        `;
                        container.appendChild(card);
                    } catch(e) {
                        console.error("Error parseando Notebook ID " + p.productId, e);
                    }
                });
            })
            .catch(error => {
                console.error("Error conectando a Logística Criterio API:", error);
                container.innerHTML = `
                    <div style="grid-column: 1/-1; padding: 3rem; background: #fee2e2; border-radius: 24px; border: 1px solid #f87171; text-align: center; color: #b91c1c;">
                        <svg style="width: 50px; height: 50px; margin: 0 auto 1rem;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                        <h3 style="font-size: 1.5rem; margin-bottom: 0.5rem;">Error de Conexión</h3>
                        <p>No pudimos sincronizar el inventario con nuestras bodegas en este momento.</p>
                    </div>
                `;
            });

        // --- MOTOR COMPACTO DE VARIACIONES DE HARDWARE ---
        window.productAPIRes = {
            ram: [
                { id:"r1", name:"8 GB", modifier:-15000, isDefault:false, status:"available" },
                { id:"r2", name:"16 GB", modifier:0, isDefault:true, status:"available" },
                { id:"r3", name:"32 GB", modifier:35000, isDefault:false, status:"available" }
            ],
            ssd: [
                { id:"s1", name:"256 GB SSD", modifier:0, isDefault:true, status:"available" },
                { id:"s2", name:"512 GB SSD", modifier:25000, isDefault:false, status:"available" },
                { id:"s3", name:"1 TB NVMe", modifier:50000, isDefault:false, status:"out_of_stock" }
            ]
        };

        window.injectCompactOptions = function(container, ops) {
            if(!container) return;
            let h = '';
            ops.forEach(o => {
                let cl = (o.isDefault) ? " selected" : "";
                let pTxt = '<span class="cd-opt-price">Base</span>';
                if(o.status === "out_of_stock") {
                    cl = " disabled";
                    pTxt = '<span class="cd-opt-price out">Agotado</span>';
                } else if(o.modifier > 0) {
                    pTxt = '<span class="cd-opt-price highlight">+ $' + Intl.NumberFormat('es-CL').format(o.modifier) + '</span>';
                } else if(o.modifier < 0) {
                    pTxt = '<span class="cd-opt-price">- $' + Intl.NumberFormat('es-CL').format(Math.abs(o.modifier)) + '</span>';
                }
                h += '<div class="cd-option-btn' + cl + '" data-price="' + o.modifier + '"><span class="cd-opt-name">' + o.name + '</span>' + pTxt + '</div>';
            });
            container.innerHTML = h;

            const btns = container.querySelectorAll('.cd-option-btn');
            btns.forEach(btn => {
                btn.addEventListener('click', () => {
                    if(btn.classList.contains('disabled')) return;
                    btns.forEach(b => b.classList.remove('selected'));
                    btn.classList.add('selected');
                    window.recalcularPrecioModal();
                });
            });
        };

        window.recalcularPrecioModal = function() {
            let m = 0;
            document.querySelectorAll('.cd-config-wrapper .cd-option-btn.selected').forEach(e => {
                m += parseInt(e.getAttribute('data-price')) || 0;
            });
            const pEl = document.getElementById('precio-modal');
            if(pEl) {
                const base = parseInt(pEl.getAttribute('data-base')) || 0;
                const fmtr = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP", maximumFractionDigits: 0 });
                pEl.innerText = fmtr.format(base + m);
            }
        };

        window.dispararCargaDeVariaciones = function(prodId) {
            // Simulamos la latencia de la DB o API real
            setTimeout(() => {
                window.injectCompactOptions(document.getElementById('modalRamOptions'), window.productAPIRes.ram);
                window.injectCompactOptions(document.getElementById('modalSsdOptions'), window.productAPIRes.ssd);
                window.recalcularPrecioModal();
            }, 600);
        };

    })();
    </script>
    
    <!-- CTA Section -->
    <section id="contacto" class="cta">
        <div class="container animate-on-scroll">
            <div class="cta-box">
                <h2>¿Dudas técnicas antes de decidirte?</h2>
                <p>Déjanos tu correo y un especialista en hardware te contactará brevemente. Responderemos preguntas técnicas de especificaciones o compatibilidad.</p>
                <div class="cta-form" id="cta-form">
                    <input type="email" id="cta-email" placeholder="Ingresa tu correo electrónico" required>
                    <button class="btn-primary" id="cta-submit">Solicitar Asesoría</button>
                </div>
                <div class="cta-success hidden" id="cta-success">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
                    <p>¡Gracias! Nos contactaremos contigo en las próximas 48 horas.</p>
                </div>
            </div>
        </div>
    </section>

    <!-- Footer -->
    <footer>
        <div class="container footer-content">
            <div class="footer-logo">
                <img src="<?php echo get_stylesheet_directory_uri(); ?>/LogoPNG.png" alt="Criterio Digital Logo" class="logo-footer">
                <p>Venta especializada de notebooks corporativos y hardware gaming testeado en Chile.</p>
            </div>
            <div class="footer-links">
                <h4>Enlaces Rápidos</h4>
                <a href="#inicio">Portada</a>
                <a href="#nosotros">Garantías y Revisión</a>
                <a href="#productos">Catálogo de Equipos</a>
            </div>
            <div class="footer-contact">
                <h4>Contacto</h4>
                <p>ventas@criteriodigital.cl</p>
                <p>Santiago, Chile</p>
            </div>
        </div>
        <div class="footer-bottom">
            <p>&copy; <?php echo date('Y'); ?> Criterio Digital. Todos los derechos reservados.</p>
        </div>
    </footer>

    <!-- Script de Animaciones y CTA -->
    <script src="<?php echo get_stylesheet_directory_uri(); ?>/script.js"></script>
    <?php wp_footer(); ?>
</body>
</html>
