<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

$db_error_message = null;
$company_name_from_db = 'Nombre de la Empresa';
$contact_phone_from_db = '';
$website_url_from_db = '';
$value_proposition_from_db = '';
$todosLosProductos = [];
$categoryCounts = [];

try {

    $company_name_from_db = 'Tienda IAStock™';
    $contact_phone_from_db = '55-1234-5678';
    $website_url_from_db = 'https://ejemplo.com';
    $value_proposition_from_db = 'Impulsa Tu Marca Con Contenido Estratégico Que Vende';

} catch (PDOException $e) {
    error_log("Error PDO al cargar configuración web: " . $e->getMessage());
    $db_error_message = 'Error de Base de Datos al cargar configuración: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("General Error al cargar configuración web: " . $e->getMessage());
    $db_error_message = 'Error inesperado al cargar configuración: ' . $e->getMessage();
}

require_once 'ia-stock/store-products.php'; // Se asume que este archivo carga $todosLosProductos

shuffle($todosLosProductos);

$initialProductsToShow = 8;
$productosIniciales = array_slice($todosLosProductos, 0, $initialProductsToShow);
$totalProducts = count($todosLosProductos);

foreach ($todosLosProductos as $p) {
    $cat = $p['category'] ?? 'Sin categoría';
    $categoryCounts[$cat] = ($categoryCounts[$cat] ?? 0) + 1;
}

arsort($categoryCounts);
$topCategories = array_slice($categoryCounts, 0, 6, true);

// --- SIMULACIÓN DE DATOS DINÁMICOS PARA LA PRUEBA SOCIAL Y URGENCIA ---
$totalSales = 2145 + count($todosLosProductos) * 5; 
$totalClients = 550 + count($topCategories) * 20; 
$daysToOfferEnd = 3; 

// Seleccionar un producto al azar para la 'Oferta del Día'
$offerProduct = $todosLosProductos[array_rand($todosLosProductos)];
$offerPrice = $offerProduct['sale_price'] ?? $offerProduct['price'];
$originalPrice = isset($offerProduct['sale_price']) ? $offerProduct['price'] : null;

// Lógica de clientes que compran (Para la simulación de pop-ups)
$customerNames = ["Laura C.", "Jorge G.", "Ana M.", "Carlos R.", "Sofía P.", "Juan V.", "María L."];
$recentSales = [];
if (!empty($todosLosProductos)) {
    for ($i = 0; $i < 7; $i++) {
        $product = $todosLosProductos[array_rand($todosLosProductos)];
        $recentSales[] = [
            'customer' => $customerNames[array_rand($customerNames)],
            'product' => htmlspecialchars($product['title']),
            'time' => rand(1, 15) // Hace 1 a 15 minutos
        ];
    }
}
// ---------------------------------------------------------------------

if (ob_get_level() > 0) {
    ob_end_clean();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title><?php echo htmlspecialchars($branding['store_name']); ?> Powered By <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>

    <style>
        /* ESTILOS BASE (Se mantienen) */
        .cat-chip { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; padding: .5rem 1rem; border-radius: 999px; border: 1px solid #e5e7eb; background: #f9fafb; color: #1f2937; font-weight: 600; transition: all .2s ease; text-decoration: none; white-space: nowrap; }
        .cat-chip:hover { background: #f3f4f6; border-color: #d1d5db; transform: translateY(-2px); }
        .cat-chip.active { background: var(--color-primary); color: #fff; border-color: var(--color-primary); }
        .cat-chip svg { width: 18px; height: 18px; }

        .asset-card { background: var(--color-primary); border: 1px solid #334155; border-radius: 16px; display: flex; flex-direction: column; transition: all .2s ease; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.06); }
        .asset-card:hover { transform: translateY(-5px); border-color: #475569; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.2), 0 4px 6px -4px rgba(0,0,0,0.1); }
        
        .asset-card__thumbnail {
            width: 100%;
            height: 150px;
            overflow: hidden;
            border-top-left-radius: 16px;
            border-top-right-radius: 16px;
            background-color: #1a2233;
            position: relative;
        }

        .asset-card__thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform .3s ease;
        }
        
        .asset-card:hover .asset-card__thumbnail img {
            transform: scale(1.05);
        }
        
        .asset-card__tag {
            position: absolute;
            top: 1rem;
            left: 1rem;
            z-index: 10;
            display: inline-flex;
            gap: .35rem;
            align-items: center;
            border-radius: 999px;
            font-weight: 700;
            text-transform: uppercase;
            font-size: .7rem;
            padding: .35rem .8rem;
            letter-spacing: .4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .asset-card__tag--popular { background: #fee2e2; color: #991b1b; }
        .asset-card__tag--new { background: #dcfce7; color: #166534; }
        
        .asset-card__content {
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }

        /* --- INICIO: CORRECCIONES DE PRECIO/OFERTA Y VENTAS (Más Llamativo y Alineado) --- */
        .asset-card__content .price-container {
            display: flex;
            justify-content: flex-end; 
            align-items: center; /* Alineado verticalmente */
            gap: 0.75rem; 
            margin-top: 1rem;
            margin-bottom: 0; 
            line-height: 1; 
        }
        
        .asset-card__content .price-container .current-price {
            font-weight: 900;
            font-size: 2.5rem; 
            color: var(--color-highlight);
            line-height: 1;
        }
        .asset-card__content .price-container .original-price {
            font-size: 1.6rem; /* ¡Más grande para el precio original! */
            color: #94a3b8;  
            text-decoration: line-through;
            align-self: center; /* Alineación al centro */
            margin-bottom: 0; 
            line-height: 1;
            white-space: nowrap;  
        }
        
        /* Contadores de Venta */
        .asset-card__sales {
            font-size: 0.8rem;
            color: #d1d5db;
            margin-top: 0.5rem;
            font-weight: 500;
            gap: 0.25rem;
            text-align: right; 
        }

        .asset-card__sales .counter-highlight {
            color: #ffffff;  
            background-color: var(--color-secondary);  
            padding: 2px 8px; 
            border-radius: 6px;
            font-size: 1.3rem; 
            line-height: 1; 
            white-space: nowrap;
            display: inline-block;
            font-family: 'Barlow', sans-serif;
            font-weight: 900;
        }
        .asset-card__sales .sales-info {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.25rem;
        }
        /* --- FIN: CORRECCIONES DE PRECIO/OFERTA Y VENTAS --- */

        .asset-card__title {
            font-weight: 800;
            font-size: 1.125rem;
            color: #f1f5f9;
            line-height: 1.3;
            margin: 0.5rem 0 0.25rem;
        }
        .asset-card__desc {
            font-size: .95rem;
            color: #94a3b8;
            line-height: 1.5;
            margin-top: 4px;
            flex-grow: 1;
            margin-bottom: 1rem;
        }
        
        /* Botón de Compra más agresivo */
        .asset-card__btn {
            display: inline-flex;
            gap: .5rem;
            align-items: center;
            justify-content: center;
            padding: .65rem 1rem;
            border-radius: 10px;
            background: var(--color-highlight);
            color: var(--color-primary);
            font-weight: 800; 
            transition: all .2s ease;
            border: none;
            text-decoration: none;
            width: 100%;
            margin-top: 1rem;
            cursor: pointer;
            box-shadow: 0 4px 15px -5px rgba(255, 170, 0, 0.7); 
        }
        .asset-card__btn:hover { 
            opacity: 1; 
            transform: scale(1.05); 
            box-shadow: 0 8px 20px -5px rgba(255, 170, 0, 0.9);
        }
        .asset-card__btn svg { width: 20px; height: 20px; }


        /* ESTILOS DE URGENCIA (Tags y Animación) */
        .asset-card__tag--hot { 
            background: #ffaa00; 
            color: #4b0000;
            font-size: .8rem;
            padding: .4rem 1rem;
            animation: pulse-tag 1.5s infinite; 
        }

        @keyframes pulse-tag {
            0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 170, 0, 0.4); }
            70% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(255, 170, 0, 0); }
            100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 170, 0, 0); }
        }

        /* ESTILOS DE PRUEBA SOCIAL Y CREDIBILIDAD */
        .stat-card { background: #ffffff; border-radius: 16px; padding: 24px; display: flex; flex-direction: column; align-items: center; text-align: center; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05); transition: all 0.2s ease; }
        .stat-card:hover { transform: translateY(-4px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1); }
        .stat-card__icon { background-color: var(--color-highlight); color: var(--color-primary); border-radius: 12px; padding: 10px; margin-bottom: 1rem; display: inline-flex; align-items: center; justify-content: center; }
        .stat-card__icon svg { width: 28px; height: 28px; }
        .stat-card__value { 
            font-size: 2.5rem; 
            font-weight: 900; 
            color: var(--color-secondary); 
            line-height: 1; 
            margin-bottom: 0.5rem; 
        }
        .stat-card__label { font-size: 0.9rem; font-weight: 600; color: #4b5563; line-height: 1.2; }

        /* --- CORRECCIÓN: Toast en Esquina Inferior Derecha --- */
        .toast-container {
            position: fixed;
            bottom: 20px;
            right: 20px; 
            left: auto; /* Asegura que no interfiera con la izquierda */
            z-index: 100;
            pointer-events: none; 
        }

        .toast {
            background-color: #fff;
            border-radius: 10px;
            padding: 1rem;
            box-shadow: 0 10px 20px rgba(0,0,0,0.2), 0 0 0 1px rgba(0,0,0,0.05);
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            max-width: 300px;
            opacity: 0;
            transform: translateX(100%); 
            transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55); 
            pointer-events: auto; 
        }
        /* --- FIN: CORRECCIÓN DE TOAST --- */

        /* --- CORRECCIÓN: Estilo de Contador de Oferta Relámpago (Más Visible) --- */
        #daily-deal #countdown-timer {
            font-size: 2.5rem; 
            font-weight: 900; 
            margin-top: 1rem;
            padding: 0.8rem 1.5rem; 
            background-color: #000000; 
            color: var(--color-highlight); 
            border-radius: 12px; 
            box-shadow: 0 5px 20px rgba(0,0,0,0.5); 
            display: flex; 
            gap: 1rem; 
            align-items: center;
            line-height: 1; 
            text-shadow: 0 0 5px rgba(255, 170, 0, 0.5); 
        }
        #daily-deal #countdown-timer span {
            display: inline-block;
            min-width: 50px; 
            text-align: center;
            border-bottom: 2px dashed rgba(255, 255, 255, 0.3); 
        }
        #daily-deal #countdown-timer .time-label {
             font-size: 0.7rem;
             display: block;
             font-weight: 600;
             margin-top: 0.25rem;
             color: #ffffff;
             text-shadow: none;
        }
        /* --- CORRECCIÓN: Precio Regular en Oferta Diaria más grande y alineado --- */
        #daily-deal .price-regular-offer {
            font-size: 1.8rem; /* Aumentado */
            line-height: 1;
            text-decoration: line-through;
            color: #d1d5db; /* Un gris más claro */
            opacity: 0.8;
            margin-bottom: 0.5rem; /* Espacio debajo */
            text-align: right;
            width: 100%;
        }
        /* --- FIN: CORRECCIÓN DE CONTADOR --- */

        /* Estilos de la CTA Personalizada (se mantienen) */
        .custom-order-section {
            background: linear-gradient(180deg, #1f2937, var(--color-primary)); 
            color: white;
            padding: 3rem;
            border-radius: 20px;
            margin-top: 3rem;
            box-shadow: 0 10px 30px -10px rgba(0,0,0,.3);
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }
        @media (min-width: 768px) {
            .custom-order-section {
                display: grid;
                grid-template-columns: 1fr 1.5fr;
                align-items: center;
                gap: 3rem;
            }
        }
        /* --- DRAWER DE PRODUCTO: Asegura visibilidad y corrige estilo --- */
        .drawer-overlay.open {
            display: block; /* Asegura que el overlay se muestre */
        }
        .drawer {
            transform: translateX(100%);
            transition: transform 0.3s ease-out;
            z-index: 40; /* Asegura que esté por encima del overlay */
        }
        .drawer.open {
            transform: translateX(0);
        }
        /* Aumento del tamaño del botón "COMPRAR AHORA Y AHORRAR" en Oferta Relámpago */
        #daily-deal .asset-card__btn {
            font-size: 1.5rem; /* Más grande */
            padding: 0.8rem 2rem; /* Más padding */
            font-weight: 900; /* Más bold */
        }

    </style>
</head>
<body data-page-title="Bienvenido A Tu Tienda Creativa AIStock™"
      data-page-subtitle="Tu Aliado De Recursos Y Activos Para Promoción"
      data-page-icon="shopping-bag">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'stock-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
            
            <div class="show-widget-container hidden">
                <button class="show-widget-btn inline-flex items-center gap-3 text-base font-bold text-white bg-[var(--color-primary)] rounded-lg shadow-lg shadow-[var(--color-primary)]/20 py-3 px-6 transform hover:-translate-y-1 hover:shadow-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--color-secondary)]"
                    data-widget-id="iastock-intro-video">
                    <i data-lucide="eye" class="w-5 h-5"></i>
                    <span>VER VIDEO PRESENTACIÓN</span>
                </button>
            </div>

        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-12">
            
            <section id="iastock-intro-video" class="p-6 md:p-10 video-widget">
                <div class="blob bl1"></div><div class="blob bl2"></div>
                <div class="relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
                    <div>
                        <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 ring-1 ring-white/15 mb-4">
                            <i data-lucide="archive" class="w-4 h-4"></i>
                            <span class="text-xs tracking-wide uppercase font-semibold">TU ALIADO CREATIVO</span>
                        </div>
                        <h1 class="text-3xl md:text-4xl font-extrabold leading-tight tracking-tight text-white">
                            <span class="text-[var(--color-highlight)]">Impulsa Tu Marca</span> Con Contenido Estratégico Que Vende
                        </h1>
                        <p class="text-white/80 mt-4 max-w-2xl text-base md:text-lg">
                            Accede a nuestra biblioteca exclusiva de imágenes, videos y plantillas diseñadas para captar la atención, generar confianza y disparar tus ventas.
                        </p>
                        <div class="mt-6 flex flex-wrap gap-3">
                            <a href="#daily-deal" class="inline-flex items-center gap-2 text-sm font-bold px-4 py-2 rounded-lg bg-[var(--color-highlight)] text-slate-900 hover:opacity-90 transition-all transform hover:scale-105">
                                <i data-lucide="zap" class="w-5 h-5"></i> VER OFERTA DEL DÍA
                            </a>
                        </div>
                    </div>

                    <div class="w-full">
                        <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                            <div class="relative w-full" style="padding-bottom: 56.25%;">
                                <video class="absolute top-0 left-0 w-full h-full object-cover" controls controlslist="nodownload nofullscreen" preload="metadata">
                                    <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                    TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                </video>
                                <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                    <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                    <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                    <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                </div>
                            </div>
                            <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                <span class="inline-flex items-center gap-2">
                                    <i data-lucide="play-circle" class="w-4 h-4"></i>
                                    Video Presentación
                                </span>

                                <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-semibold text-red-400 hover:text-red-300 transition-colors py-1 px-2 rounded-md" 
                                        data-widget-id="iastock-intro-video" 
                                        title="Ocultar el video de bienvenida">
                                    OCULTAR VIDEO
                                    <i data-lucide="x" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            
            <section id="ia-stock-stats" class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <article class="stat-card">
                    <div class="stat-card__icon"><i data-lucide="users" class="w-7 h-7"></i></div>
                    <div class="stat-card__value"><?php echo number_format($totalClients, 0, ',', '.'); ?>+</div>
                    <div class="stat-card__label">CLIENTES SATISFECHOS</div>
                </article>
                <article class="stat-card">
                    <div class="stat-card__icon"><i data-lucide="sparkles" class="w-7 h-7"></i></div>
                    <div class="stat-card__value"><?php echo $totalProducts; ?>+</div>
                    <div class="stat-card__label">ACTIVOS CREATIVOS LISTOS</div>
                </article>
                <article class="stat-card">
                    <div class="stat-card__icon"><i data-lucide="zap" class="w-7 h-7"></i></div>
                    <div class="stat-card__value"><?php echo number_format($totalSales, 0, ',', '.'); ?>+</div>
                    <div class="stat-card__label">VENTAS REALIZADAS</div>
                </article>
            </section>

            <section id="daily-deal" class="bg-[var(--color-secondary)] p-6 md:p-8 rounded-xl text-white shadow-xl transform hover:scale-[1.005] transition-all duration-300">
                <div class="flex flex-col md:flex-row justify-between items-center gap-6">
                    <div class="flex flex-col md:flex-row items-center gap-4 flex-1">
                        <i data-lucide="bomb" class="w-12 h-12 flex-shrink-0 text-[var(--color-highlight)]"></i>
                        <div>
                            <span class="text-xl font-extrabold uppercase block leading-none">⚡️ OFERTA RELÁMPAGO DEL DÍA</span>
                            <h4 class="text-3xl font-black uppercase mt-1 leading-none text-white"><?php echo htmlspecialchars($offerProduct['title']); ?></h4>
                        </div>
                    </div>
                    
                    <div class="flex flex-col items-center md:items-end flex-shrink-0">
                        <?php if ($originalPrice): ?>
                            <p class="price-regular-offer">Precio Regular: $<?php echo htmlspecialchars($originalPrice); ?></p>
                        <?php endif; ?>
                        <p class="text-6xl font-black leading-none text-[var(--color-highlight)]">$<?php echo htmlspecialchars($offerPrice); ?></p>
                        <div id="countdown-timer">
                            <span id="hours"><div class="time-label">HRS</div></span>:
                            <span id="minutes"><div class="time-label">MIN</div></span>:
                            <span id="seconds"><div class="time-label">SEG</div></span>
                        </div>
                    </div>

                    <div class="w-full md:w-auto flex-shrink-0">
                         <?php 
                            $offerDataAttrs = [
                                "data-title" => htmlspecialchars($offerProduct['title']),
                                "data-description" => htmlspecialchars($offerProduct['description'] ?? '¡Aprovecha esta oferta limitada!'),
                                "data-type" => htmlspecialchars($offerProduct['category'] ?? 'Oferta Especial'),
                                "data-content" => htmlspecialchars($offerProduct['content_type'] ?? 'Descarga Inmediata'),
                                "data-price" => htmlspecialchars('$' . $offerPrice),
                                "data-is-digital" => 'true',
                                "data-icon-name" => 'zap',
                            ];
                            $offerDataHtml = implode(' ', array_map(
                                fn($k, $v) => "{$k}=\"" . str_replace('"', '&quot;', $v) . "\"",
                                array_keys($offerDataAttrs),
                                array_values($offerDataAttrs)
                            ));
                        ?>
                        <button type="button"
                            class="asset-card__btn bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold text-lg py-3 hover:opacity-100 hover:scale-100 transition-none w-full md:w-auto"
                            onclick="openProductDrawerFromButton(this)"
                            <?php echo $offerDataHtml; ?>
                        >
                            <i data-lucide="bolt" class="w-6 h-6"></i> ¡COMPRAR AHORA Y AHORRAR!
                        </button>
                    </div>
                </div>
            </section>

            <section id="ia-stock-latest">
                <h3 class="text-2xl font-extrabold text-gray-800 mb-6" style="color: var(--color-primary);">NOVEDADES QUE DISPARAN TUS VENTAS</h3>
                <div id="product-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-6">
                    <?php foreach ($productosIniciales as $producto): ?>
                        <?php
                            // Lógica de tags de urgencia/tendencia
                            $tag_urgency = '';
                            $current_stock = $producto['stock'] ?? 10; 
                            $sold_units = $producto['sold_units'] ?? 0;
                            $status = $producto['status'] ?? '';

                            if ($current_stock < 5) {
                                // FOMO/Urgencia por bajo stock
                                $tag_urgency = '<span class="asset-card__tag asset-card__tag--hot">🔥 ÚLTIMAS UNIDADES</span>';
                            } elseif ($sold_units > 200 && $status !== 'popular') {
                                // Prueba social por alto volumen de ventas
                                $tag_urgency = '<span class="asset-card__tag asset-card__tag--popular">📈 EN TENDENCIA</span>';
                            }
                        ?>
                        <article class="asset-card">
                            <div class="asset-card__thumbnail">
                                <img src="<?php echo 'ia-stock/' . htmlspecialchars($producto['mockup_image'] ?? ''); ?>" alt="Mockup de <?php echo htmlspecialchars($producto['title']); ?>">
                                
                                <?php if ($tag_urgency): ?>
                                    <?php echo $tag_urgency; ?>
                                <?php elseif (isset($producto['status'])): ?>
                                    <span class="asset-card__tag <?php echo $producto['status'] === 'popular' ? 'asset-card__tag--popular' : 'asset-card__tag--new'; ?>">
                                        <?php echo $producto['status'] === 'popular' ? 'POPULAR' : 'NUEVO'; ?>
                                    </span>
                                <?php endif; ?> 
                            </div>
                            <div class="asset-card__content flex flex-col justify-between p-4">
                                <div class="mb-4">
                                    <h4 class="asset-card__title text-3xl font-black uppercase"><?php echo htmlspecialchars($producto['title']); ?></h4>
                                    <p class="asset-card__desc"><?php echo htmlspecialchars($producto['description']); ?></p>
                                </div>
                                
                                <div class="flex flex-col items-end pt-2 pb-1">
                                    <div class="price-container"> 
                                        <?php if (isset($producto['sale_price'])): ?>
                                            <span class="original-price">$<?php echo htmlspecialchars($producto['price']); ?></span>
                                            <span class="current-price">$<?php echo htmlspecialchars($producto['sale_price']); ?></span>
                                        <?php else: ?>
                                            <span class="current-price">$<?php echo htmlspecialchars($producto['price']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <?php if (isset($producto['sold_units'])): ?>
                                    <div class="asset-card__sales pt-1">
                                        <div class="sales-info">
                                            <i data-lucide="zap" class="w-4 h-4 text-gray-300"></i>
                                            <span class="counter-highlight"><?php echo htmlspecialchars($producto['sold_units']); ?>+</span>
                                        </div>
                                        <span class="text-gray-400 text-xs uppercase leading-none mt-1">Unidades Vendidas</span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php
                                    $productTitle = htmlspecialchars($producto['title']);
                                    $productDesc = htmlspecialchars($producto['description']);
                                    $productCategory = htmlspecialchars($producto['category'] ?? 'Recurso Digital');
                                    $productContent = htmlspecialchars($producto['content_type'] ?? 'Descarga Inmediata (ZIP/MP4)');
                                    $productPriceDisplay = isset($producto['sale_price']) ? htmlspecialchars('$' . $producto['sale_price']) : htmlspecialchars('$' . $producto['price']);
                                    $isDigital = 'true'; 

                                    $iconNameForDrawer = match($productCategory) {
                                        'Video' => 'video',
                                        'Audio' => 'headphones',
                                        'Documento' => 'file-text',
                                        'Plantilla' => 'layout-template',
                                        default => 'image',
                                    };
                                    $dataAttrs = [
                                        "data-title" => $productTitle,
                                        "data-description" => $productDesc,
                                        "data-type" => $productCategory,
                                        "data-content" => $productContent,
                                        "data-price" => $productPriceDisplay,
                                        "data-is-digital" => $isDigital,
                                        "data-icon-name" => $iconNameForDrawer,
                                    ];
                                    $dataHtml = implode(' ', array_map(
                                        fn($k, $v) => "{$k}=\"" . str_replace('"', '&quot;', $v) . "\"",
                                        array_keys($dataAttrs),
                                        array_values($dataAttrs)
                                    ));
                                ?>
                                    <button type="button"
                                        class="asset-card__btn"
                                        onclick="openProductDrawerFromButton(this)"
                                        <?php echo $dataHtml; ?>
                                    >
                                        <i data-lucide="bolt" class="w-5 h-5"></i> ¡LO QUIERO AHORA!
                                    </button>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
                <div id="load-more-container" class="flex justify-center mt-8">
                    <button id="load-more-btn" class="bg-[var(--color-primary)] text-white font-extrabold py-3 px-8 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2">
                        CARGAR MÁS PRODUCTOS (<?php echo $totalProducts - $initialProductsToShow; ?> RESTANTES)
                    </button>
                </div>
            </section>

            <hr class="my-12 border-gray-300">

            <section class="custom-order-section">
                <div class="cta-text">
                    <div class="inline-flex items-center gap-3 text-white mb-4">
                        <h2 class="text-3xl md:text-4xl lg:text-5xl font-extrabold leading-tight">¿Tienes un Proyecto Exclusivo en Mente?</h2>
                    </div>
                    <h3 class="text-xl md:text-2xl font-extrabold leading-tight text-white mb-4">
                        <span class="text-[var(--color-highlight)]">Transforma Tu <b>Visión En Realidad</b></span>
                    </h3>
                    <p class="mt-4 text-gray-300 max-w-lg mb-6">
                        Deja de buscar y empieza a crear. Nuestro equipo de expertos está listo para diseñar un activo digital <b>único para tu negocio</b>, que eleve tu marca y te diferencie de la competencia.
                    </p>
                    
                    <ul class="space-y-3">
                        <li class="flex items-center gap-2 text-white">
                            <i data-lucide="check-circle-2" class="w-6 h-6 text-green-500"></i>
                            <span class="text-lg font-bold">Un diseño 100% original para tu marca.</span>
                        </li>
                        <li class="flex items-center gap-2 text-white">
                            <i data-lucide="check-circle-2" class="w-6 h-6 text-green-500"></i>
                            <span class="text-lg font-bold">Sin necesidad de conocimientos técnicos.</span>
                        </li>
                        <li class="flex items-center gap-2 text-white">
                            <i data-lucide="check-circle-2" class="w-6 h-6 text-green-500"></i>
                            <span class="text-lg font-bold">Entrega garantizada y soporte de expertos.</span>
                        </li>
                    </ul>
                </div>
                <form class="custom-order-form" method="POST" action="send_order.php">
                    <h3 class="text-xl font-bold mb-4 flex items-center gap-2"><i data-lucide="send"></i> Trabajemos En Tu Proyecto Único y Personalizado</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="name" class="text-sm font-semibold mb-1 block text-white">Tu Nomobre Comleto</label>
                            <input type="text" id="name" name="name" required class="w-full p-3 rounded-lg bg-gray-100 border border-gray-300 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-transparent" placeholder="Ej: Mario Gómez">
                        </div>
                        <div>
                            <label for="email" class="text-sm font-semibold mb-1 block text-white">Correo Electrónico</label>
                            <input type="email" id="email" name="email" required class="w-full p-3 rounded-lg bg-gray-100 border border-gray-300 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-transparent" placeholder="tucorreo@ejemplo.com">
                        </div>
                    </div>
                    <div class="mb-4">
                        <label for="project-type" class="text-sm font-semibold mb-1 block text-white">Tipo De Proyecto</label>
                        <input type="text" id="project-type" name="project-type" placeholder="Ej: Video para TikTok, Logo, Banners para redes, etc." required class="w-full p-3 rounded-lg bg-gray-100 border border-gray-300 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-transparent">
                    </div>
                    <div class="mb-4">
                        <label for="details" class="text-sm font-semibold mb-1 block text-white">Cuéntanos Sobre Tu Idea</label>
                        <textarea id="details" name="details" rows="4" required class="w-full p-3 rounded-lg bg-gray-100 border border-gray-300 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-transparent" placeholder="Descripción detallada de tu proyecto..."></textarea>
                    </div>
                    <button type="submit" class="w-full py-3 bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold rounded-lg hover:brightness-110 transition flex items-center justify-center gap-2">
                        <i data-lucide="sparkles" class="w-5 h-5"></i> ¡SI, QUIERO ALGO PERZONALIZADO!
                    </button>
                </form>
            </section>
        </div>
    </main>
    
    <div id="product-drawer-overlay" class="drawer-overlay fixed inset-0 bg-gray-900 bg-opacity-75 hidden" onclick="closeProductDrawer()"></div>
    
    <div id="product-drawer" class="drawer fixed top-0 right-0 w-full md:w-1/3 h-full bg-white shadow-2xl overflow-y-auto p-6 flex flex-col justify-between">       
        <div class="flex-1">
            <div class="flex justify-between items-center mb-6 border-b-2 border-gray-100 pb-4">
                <div id="drawer-icon-container" class="p-2 rounded-lg mr-3 flex items-center" style="background-color: var(--color-primary);">
                     </div>
                                            <h2 id="drawer-title" class="text-2xl font-extrabold flex-1 font-barlow" style="color: var(--color-primary);"></h2>
                <button onclick="closeProductDrawer()" class="p-2 rounded-full hover:bg-gray-100 text-gray-700 transition">
                       <i data-lucide="x" class="w-6 h-6"></i>
                </button>
            </div>
            
            <p id="drawer-description" class="mb-6 text-gray-600 font-barlow leading-relaxed"></p>
            
            <div class="space-y-4 mb-8 p-4 rounded-lg bg-gray-50 border border-gray-200">
                                            <h3 class="text-lg font-bold flex items-center font-barlow" style="color: var(--color-secondary);">
                         <i data-lucide="settings" class="w-5 h-5 mr-2"></i> ESPECIFICACIONES TÉCNICAS
                </h3>
                <div class="flex justify-between border-b pb-2">
                    <span class="text-sm font-medium text-gray-500 font-barlow">TIPO DE ACTIVO:</span>
                                                        <span id="drawer-type" class="text-sm font-semibold font-barlow" style="color: var(--color-primary);"></span>
                </div>
                <div class="flex justify-between border-b pb-2">
                    <span class="text-sm font-medium text-gray-500 font-barlow">FORMATO/ENTREGA:</span>
                                                        <span id="drawer-content" class="text-sm font-semibold font-barlow" style="color: var(--color-primary);"></span>
                </div>
                
                <div class="flex justify-between items-center pt-2">
                    <span class="text-xl font-bold text-gray-700 font-barlow">INVERSIÓN:</span>
                                                        <span id="drawer-price" class="text-2xl font-extrabold font-barlow" style="color: var(--color-secondary);"></span>
                </div>
            </div>
            
                                                <h3 class="text-xl font-bold flex items-center mb-4 font-barlow" style="color: var(--color-primary);">
                         <i data-lucide="award" class="w-6 h-6 mr-2" style="color: var(--color-highlight);"></i> BENEFICIOS CLAVE
                </h3>
            
            <ul class="space-y-3 text-gray-700 mb-8 list-none pl-0">
                <li class="flex items-start font-barlow">
                                                        <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0" style="color: var(--color-highlight);"></i> 
                    Derechos de uso profesional y comercial para su negocio.
                </li>
                <li class="flex items-start font-barlow">
                    <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0" style="color: var(--color-highlight);"></i> 
                    Soporte técnico prioritario sobre la implementación del recurso.
                </li>
                <li class="flex items-start font-barlow">
                    <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0" style="color: var(--color-highlight);"></i> 
                    Garantía de cumplimiento con los estándares de su mercado.
                </li>
                <li id="drawer-bonus" class="flex items-start font-barlow">
                     </li>
            </ul>

        </div>
        
        <div class="mt-6 pt-4 border-t border-gray-100">
                             <button id="drawer-buy-button" class="w-full text-lg p-3 rounded-xl text-white font-bold btn-secondary">
                          <i data-lucide="credit-card" class="w-5 h-5 mr-2 inline-block align-text-bottom"></i> 
                     PROCEDER A LA ADQUISICIÓN
                   </button>
                 <p id="drawer-delivery-notice" class="text-xs text-center mt-2 text-gray-500 font-barlow"></p>
               </div>
          
       </div>
    
    <script>
        // LÓGICA DE CARGA DE PRODUCTOS ADICIONALES (Se mantiene)
        document.addEventListener('DOMContentLoaded', () => {
            const allProductsData = <?php echo json_encode($todosLosProductos, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
            const loadMoreBtn = document.getElementById('load-more-btn');
            const productGrid = document.getElementById('product-grid');
            const itemsPerPage = 8;
            let currentPage = 1;

            const createCardHTML = (product) => {
                const statusClass = product.status === 'popular' ? 'asset-card__tag--popular' : 'asset-card__tag--new';
                const statusText = product.status === 'popular' ? 'POPULAR' : 'NUEVO';
                const mockupPath = product.mockup_image ? `ia-stock/${product.mockup_image}` : 'data:image/svg+xml,%3Csvg%20xmlns=\'http://www.w3.org/2000/svg\'%20viewBox=\'0%200%20240%20180\'%20fill=\'none\'%20stroke=\'#374151\'%20stroke-width=\'2\'%3E%3Crect%20x=\'1\'%20y=\'1\'%20width=\'238\'%20height=\'178\'%20rx=\'10\'/%3E%3Cpath%20d=\'M40%20120%20L90%2070%20C92%2068%2095%2068%2097%2070%20L140%20113%20C142%20115%20145%20115%20147%20113%20L190%2070\'/%3E%3C/svg%3E';
                
                const productCategory = product.category || 'Recurso Digital';
                const productContent = product.content_type || 'Descarga Inmediata (ZIP/MP4)';
                const isDigital = 'true';
                const productIconName = {
                    'Video': 'video',
                    'Audio': 'headphones',
                    'Documento': 'file-text',
                    'Plantilla': 'layout-template',
                    'Imagen': 'image',
                }[productCategory] || 'image'; 

                const finalPrice = product.sale_price ? `$${product.sale_price}` : `$${product.price}`;

                const priceHTML = product.sale_price ?
                    `<span class="original-price">$${product.price}</span><span class="current-price">$${product.sale_price}</span>` :
                    `<span class="current-price">$${product.price}</span>`;
                
                const dataAttrs = `
                    data-title="${product.title.replace(/"/g, '&quot;')}"
                    data-description="${product.description.replace(/"/g, '&quot;')}"
                    data-type="${productCategory.replace(/"/g, '&quot;')}"
                    data-content="${productContent.replace(/"/g, '&quot;')}"
                    data-price="${finalPrice.replace(/"/g, '&quot;')}"
                    data-is-digital="${isDigital}"
                    data-icon-name="${productIconName}"
                `;

                // Lógica de tags de urgencia (la misma que en PHP)
                let urgencyTagHTML = '';
                if (product.stock < 5) {
                    urgencyTagHTML = '<span class="asset-card__tag asset-card__tag--hot">🔥 ÚLTIMAS UNIDADES</span>';
                } else if (product.sold_units > 200 && product.status !== 'popular') {
                    urgencyTagHTML = '<span class="asset-card__tag asset-card__tag--popular">📈 EN TENDENCIA</span>';
                } else if (product.status) {
                    // Si no hay urgencia, pero hay status (popular/nuevo)
                    urgencyTagHTML = `<span class="asset-card__tag ${statusClass}">
                        ${statusText}
                    </span>`;
                }
                
                // CORRECCIÓN: Estructura de ventas en el JS
                const salesHTML = product.sold_units ?  
                    `<div class="asset-card__sales pt-1">
                        <div class="sales-info">
                            <i data-lucide="zap" class="w-4 h-4 text-gray-300"></i>
                            <span class="counter-highlight">${product.sold_units}+</span>
                        </div>
                        <span class="text-gray-400 text-xs uppercase leading-none mt-1">Unidades Vendidas</span>
                    </div>` : '';

                return `
                <article class="asset-card">
                    <div class="asset-card__thumbnail">
                        <img src="${mockupPath}" alt="Mockup de ${product.title}">
                        ${urgencyTagHTML}
                    </div>
                    <div class="asset-card__content flex flex-col justify-between p-4">
                        <div class="mb-4">
                            <h4 class="asset-card__title">${product.title}</h4>
                            <p class="asset-card__desc">${product.description}</p>
                        </div>
                        
                        <div class="flex flex-col items-end pt-2 pb-1">
                            <div class="price-container"> 
                                ${priceHTML}
                            </div>
                        </div>

                        ${salesHTML}
                        
                        <button type="button"
                            class="asset-card__btn"
                            onclick="openProductDrawerFromButton(this)"
                            ${dataAttrs}
                        >
                            <i data-lucide="bolt" class="w-5 h-5"></i> ¡LO QUIERO AHORA!
                        </button>
                    </div>
                </article>`;
            };

            if (allProductsData.length <= itemsPerPage) {
                loadMoreBtn.style.display = 'none';
            }

            loadMoreBtn.addEventListener('click', () => {
                loadMoreBtn.textContent = 'Cargando…';
                loadMoreBtn.disabled = true;

                setTimeout(() => {
                    const start = currentPage * itemsPerPage;
                    const end = start + itemsPerPage;
                    const newProducts = allProductsData.slice(start, end);

                    if (newProducts.length === 0) {
                        loadMoreBtn.style.display = 'none';
                        return;
                    }

                    const frag = document.createElement('div');
                    frag.innerHTML = newProducts.map(createCardHTML).join('');
                    const cards = Array.from(frag.children);
                    cards.forEach(card => productGrid.appendChild(card));
                    lucide.createIcons();

                    currentPage++;
                    const remainingProducts = allProductsData.length - (currentPage * itemsPerPage);
                    loadMoreBtn.textContent = `CARGAR MÁS PRODUCTOS (${Math.max(0, remainingProducts)} RESTANTES)`;
                    loadMoreBtn.disabled = false;

                    if (remainingProducts <= 0) {
                        loadMoreBtn.style.display = 'none';
                    }
                }, 400);
            });
        });
    </script>
    
    <script>
        // LÓGICA DE WIDGETS Y VIDEO (Se mantiene)
        document.addEventListener('DOMContentLoaded', () => {

            const toggleWidgetVisibility = (widgetId, isHidden) => {
                const widget = document.getElementById(widgetId);
                const showContainer = document.querySelector(`.show-widget-btn[data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
                const videoPlayer = widget ? widget.querySelector('video') : null;

                if (!widget || !showContainer) return; 

                if (isHidden) {
                    widget.classList.add('hidden');
                    showContainer.classList.remove('hidden');
                    if (videoPlayer) videoPlayer.pause(); 
                } else {
                    widget.classList.remove('hidden');
                    showContainer.classList.add('hidden');
                }

                localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
            };

            document.querySelectorAll('.hide-widget-btn').forEach(button => {
                button.addEventListener('click', (event) => {
                    const widgetId = event.currentTarget.dataset.widgetId; 
                    toggleWidgetVisibility(widgetId, true); 
                });
            });

            document.querySelectorAll('.show-widget-btn').forEach(button => {
                button.addEventListener('click', (event) => {
                    const widgetId = event.currentTarget.dataset.widgetId; 
                    toggleWidgetVisibility(widgetId, false); 
                });
            });

            document.querySelectorAll('.video-widget').forEach(widget => {
                const widgetId = widget.id;
                const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
                if (isHidden) {
                    toggleWidgetVisibility(widgetId, true);
                }
            });
        });

        // LÓGICA DEL DRAWER (Se mantiene y se corrige)
        function openProductDrawerFromButton(button) {
            const title = button.getAttribute('data-title');
            const description = button.getAttribute('data-description');
            const type = button.getAttribute('data-type');
            const content = button.getAttribute('data-content');
            const price = button.getAttribute('data-price');
            const isDigital = button.getAttribute('data-is-digital') === 'true';
            const iconName = button.getAttribute('data-icon-name');
            
            openProductDrawer(title, description, type, content, price, isDigital, iconName);
        }

        function openProductDrawer(title, description, type, content, price, isDigital, iconName) {
            document.getElementById('drawer-title').innerText = title.toUpperCase();
            document.getElementById('drawer-description').innerText = description;
            document.getElementById('drawer-type').innerText = type.toUpperCase();
            document.getElementById('drawer-content').innerText = content;
            document.getElementById('drawer-price').innerText = price;
            
            const deliveryNotice = document.getElementById('drawer-delivery-notice');
            const bonusItem = document.getElementById('drawer-bonus');
            const iconContainer = document.getElementById('drawer-icon-container');
            const highlightColor = 'white'; // Color del ícono en el drawer

            // Asegura que el contenedor del icono se limpie y se vuelva a crear
            iconContainer.innerHTML = `<i data-lucide="${iconName}" class="w-7 h-7" style="color: ${highlightColor};"></i>`;

            if (isDigital) {
                deliveryNotice.innerText = 'Entrega digital instantánea 24/7.';
                bonusItem.innerHTML = `<i data-lucide="download-cloud" class="w-5 h-5 mr-3 mt-1 flex-shrink-0" style="color: var(--color-highlight);"></i>
                                        Acceso directo e ilimitado a la descarga en la sección Mi Cuenta.`;
            } else {
                deliveryNotice.innerText = 'Producto impreso. El envío está sujeto a los tiempos de logística (3-5 días).';
                bonusItem.innerHTML = `<i data-lucide="truck" class="w-5 h-5 mr-3 mt-1 flex-shrink-0" style="color: var(--color-highlight);"></i>
                                        Servicio de seguimiento de envío incluido en la compra.`;
            }

            document.getElementById('product-drawer').classList.add('open');
            document.getElementById('product-drawer-overlay').classList.add('open');
            document.getElementById('product-drawer-overlay').classList.remove('hidden');
            
            lucide.createIcons(); // Vuelve a crear los íconos Lucide dentro del drawer
        }

        function closeProductDrawer() {
            document.getElementById('product-drawer').classList.remove('open');
            document.getElementById('product-drawer-overlay').classList.remove('open');
            setTimeout(() => {
                   document.getElementById('product-drawer-overlay').classList.add('hidden');
            }, 300); 
        }

        // SCRIPT DE PRUEBA SOCIAL (TOASTS) Y CONTADOR REGRESIVO (OFERTA)
        const recentSalesData = <?php echo json_encode($recentSales, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
        const toastContainer = document.getElementById('toast-container');

        const showSaleToast = (sale) => {
            const toast = document.createElement('div');
            toast.className = 'toast show';
            toast.innerHTML = `
                <i data-lucide="check-circle" class="w-5 h-5 text-green-500 flex-shrink-0 mr-2"></i>
                <div class="text-sm">
                    <p class="font-bold">${sale.customer}</p>
                    <p class="text-gray-700">Compró <span class="font-extrabold text-[var(--color-primary)]">${sale.product}</span> hace ${sale.time} min.</p>
                </div>
            `;
            toastContainer.appendChild(toast);
            lucide.createIcons(); 

            setTimeout(() => {
                toast.classList.remove('show');
                toast.classList.add('hide');
                setTimeout(() => toast.remove(), 500); 
            }, 5000);
        };

        const startSaleToastLoop = () => {
            let salesIndex = 0;
            const interval = 12000; // Muestra una notificación cada 12 segundos

            setInterval(() => {
                const sale = recentSalesData[salesIndex % recentSalesData.length];
                showSaleToast(sale);
                salesIndex++;
            }, interval);
        };

        // Contador Regresivo (Para la sección de Oferta Relámpago)
        const startCountdown = () => {
            const endDate = new Date();
            endDate.setDate(endDate.getDate() + <?php echo $daysToOfferEnd; ?>); 
            endDate.setHours(23, 59, 59, 999); 

            const timer = setInterval(() => {
                const now = new Date().getTime();
                const distance = endDate - now;

                const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                const formatTime = (t) => t.toString().padStart(2, '0');
                
                // Actualiza los elementos HTML del contador
                document.getElementById("hours").innerHTML = formatTime(hours + (days * 24)) + '<div class="time-label">HRS</div>';
                document.getElementById("minutes").innerHTML = formatTime(minutes) + '<div class="time-label">MIN</div>';
                document.getElementById("seconds").innerHTML = formatTime(seconds) + '<div class="time-label">SEG</div>';

                if (distance < 0) {
                    clearInterval(timer);
                    document.getElementById("countdown-timer").innerHTML = "¡LA OFERTA HA EXPIRADO!";
                    document.querySelector('#daily-deal .asset-card__btn').disabled = true;
                }
            }, 1000);
        };

        window.onload = function() {
            lucide.createIcons();

            if (recentSalesData.length > 0) {
                startSaleToastLoop();
            }
            startCountdown();
        };

    </script>
<script src="files/toast.js"></script>
</body>
</html>