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

$db_error_message = null;
$company_name_from_db = 'De Todo En Publicidad™';
$contact_phone_from_db = '425-777-2109';
$website_url_from_db = 'https://ejemplo.com';
$value_proposition_from_db = 'Impulsa Tu Marca Con Contenido Estratégico Que Vende';
$todosLosProductos = [];

if (empty($todosLosProductos)) {
    $todosLosProductos = [
        [
            'id' => 1, 'title' => 'Producto de Ejemplo (Digital)', 'description' => 'Descripción de ejemplo. Recurso listo para usar.', 'price' => 100, 'sale_price' => 80,
            'category' => 'Digital', 'mockup_image' => 'https://siteflow.generamasclientes.com/img/SiteFlowLight.webp', 'stock' => 10, 'sold_units' => 50, 'status' => 'popular', 'content_type' => 'Descarga Digital',
            'main_section' => 'Productos Digitales'
        ],
        [
            'id' => 2, 'title' => 'Otro Producto (Plantilla)', 'description' => 'Otra descripción de plantilla de alto impacto.', 'price' => 250, 'sale_price' => 200,
            'category' => 'Plantilla', 'mockup_image' => 'https://siteflow.generamasclientes.com/img/SiteFlowLight.webp', 'stock' => 100, 'sold_units' => 20, 'status' => 'new', 'content_type' => 'Descarga (ZIP)',
            'main_section' => 'Productos Digitales'
        ],
        [
            'id' => 3, 'title' => 'Tarjetas de Presentación', 'description' => 'Mil tarjetas de presentación con acabado premium laminado mate y barniz a registro.', 'price' => 500,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/tarjetas.jpg', 'stock' => 100, 'sold_units' => 120, 'status' => 'new', 'content_type' => 'Envío Físico (1 millar)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 4, 'title' => 'Volantes Publicitarios', 'description' => 'Impresión de 1000 volantes full color en papel couché de 150g, tamaño media carta.', 'price' => 800, 'sale_price' => 750,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/volantes.jpg', 'stock' => 100, 'sold_units' => 250, 'status' => 'popular', 'content_type' => 'Envío Físico (1 millar)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 5, 'title' => 'Lona Publicitaria', 'description' => 'Lona de alta resolución 1200dpi, ideal para exteriores. Medida de 3x2 metros con ojillos.', 'price' => 600,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/lona.jpg', 'stock' => 50, 'sold_units' => 80, 'status' => 'new', 'content_type' => 'Envío Físico (1 pieza)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 6, 'title' => 'Stickers Personalizados', 'description' => 'Paquete de 500 stickers de vinil con corte a registro. Resistentes al agua y sol.', 'price' => 450, 'sale_price' => 400,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/stickers.jpg', 'stock' => 100, 'sold_units' => 300, 'status' => 'popular', 'content_type' => 'Envío Físico (500 piezas)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 7, 'title' => 'Menús para Restaurante', 'description' => '10 Menús tamaño carta en PVC rígido, impresión full color por ambos lados, alta durabilidad.', 'price' => 1200,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/menu.jpg', 'stock' => 30, 'sold_units' => 45, 'status' => 'new', 'content_type' => 'Envío Físico (10 piezas)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 8, 'title' => 'Playeras con Serigrafía', 'description' => 'Paquete de 20 playeras de algodón con tu logo impreso a una tinta en serigrafía.', 'price' => 2500,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/playeras.jpg', 'stock' => 20, 'sold_units' => 15, 'status' => 'new', 'content_type' => 'Envío Físico (20 playeras)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 9, 'title' => 'Roll-Up Banner', 'description' => 'Estructura de aluminio tipo Roll-Up con gráfico impreso en lona de alta calidad. Incluye bolsa de transporte.', 'price' => 950, 'sale_price' => 899,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/rollup.jpg', 'stock' => 40, 'sold_units' => 90, 'status' => 'popular', 'content_type' => 'Envío Físico (1 pieza)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 10, 'title' => 'Folletos Trípticos', 'description' => '1000 Folletos trípticos tamaño carta, full color ambos lados en couché de 135g.', 'price' => 1100,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/triptico.jpg', 'stock' => 100, 'sold_units' => 60, 'status' => 'new', 'content_type' => 'Envío Físico (1 millar)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 11, 'title' => 'Notas de Remisión', 'description' => 'Block de 100 notas de remisión foliadas en papel autocopiante (original y copia).', 'price' => 350,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/notas.jpg', 'stock' => 100, 'sold_units' => 110, 'status' => 'new', 'content_type' => 'Envío Físico (1 block)',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 12, 'title' => 'Tazas Personalizadas', 'description' => 'Caja con 12 tazas de cerámica blancas de 11oz impresas con tu diseño en sublimación.', 'price' => 700,
            'category' => 'Impresión', 'mockup_image' => 'img/impresos/tazas.jpg', 'stock' => 50, 'sold_units' => 75, 'status' => 'new', 'content_type' => 'Envío Físico (12 tazas)',
            'main_section' => 'Productos Impresos'
        ],
    ];
}

shuffle($todosLosProductos);

function shuffle_and_get($array) {
    shuffle($array);
    return $array;
}

// Lógica de filtrado
$seccionesData = [];
foreach ($todosLosProductos as $p) {
    $seccion = $p['main_section'] ?? null;
    if ($seccion) {
        $seccionesData[$seccion][] = $p;
    }
}


$productosDeEstaSeccion = $seccionesData['Productos Impresos'] ?? [];

$customerNames = ["Laura C.", "Jorge G.", "Ana M.", "Carlos R.", "Sofía P.", "Juan V.", "María L."];
$recentSales = [];
$company_name = $company_name_from_db; 
$statuses = ["Compra Confirmada", "Procesando Pago", "Producto Enviado"];

if (!empty($todosLosProductos)) {
    for ($i = 0; $i < 7; $i++) {
        $product = $todosLosProductos[array_rand($todosLosProductos)];
        $img_url = htmlspecialchars($product['mockup_image'] ?? 'img/default.jpg');
        if (!str_contains($img_url, 'http') && !str_starts_with($img_url, '/')) {
             $img_url = 'ia-stock/' . $img_url; 
        }
        
        $recentSales[] = [
            'customer' => $customerNames[array_rand($customerNames)],
            'product' => htmlspecialchars($product['title']),
            'time' => rand(1, 15),
            'image' => $img_url, 
            'business' => htmlspecialchars($company_name),
            'status' => $statuses[array_rand($statuses)] 
        ];
    }
}

function renderMiniProductCard($prod, $seccionName) {
    $is_digital = (($prod['main_section'] ?? '') === 'Productos Digitales') ? 'true' : 'false';
    $icon_map = [
        'Digital' => 'cloud-download', 'Plantilla' => 'layers', 'Impresión' => 'printer',
        'Servicio' => 'megaphone', 'Curso' => 'graduation-cap', 'Programa' => 'trending-up',
        'Recurso' => 'archive',
    ];
    $icon_name = $icon_map[$prod['category'] ?? 'Recurso'] ?? 'archive';

    $is_local = !str_contains($prod['mockup_image'] ?? '', 'http');
    $img_src = $is_local ? ('dtep/' . htmlspecialchars($prod['mockup_image'] ?? 'img/default.jpg')) : htmlspecialchars($prod['mockup_image'] ?? 'img/default.jpg');
    
    $title = htmlspecialchars($prod['title']);
    $current_price = htmlspecialchars($prod['sale_price'] ?? $prod['price']);
    $original_price_val = isset($prod['sale_price']) ? htmlspecialchars($prod['price']) : null;
    $original_price = $original_price_val ? '$' . $original_price_val : ''; 
    $pay_url = "pay.php?product_id=" . htmlspecialchars($prod['id']) . "&price=" . $current_price; 

    $data_attrs = [
        "data-title" => $title,
        "data-description" => htmlspecialchars($prod['description']),
        "data-type" => htmlspecialchars($prod['category'] ?? 'Producto'),
        "data-content" => htmlspecialchars($prod['content_type'] ?? 'Activo Digital'),
        "data-price" => '$' . $current_price,
        "data-is-digital" => $is_digital,
        "data-icon-name" => $icon_name,
        "data-pay-url" => $pay_url, 
    ];

    $data_html = implode(' ', array_map(
        fn($k, $v) => "{$k}=\"" . str_replace('"', '&quot;', $v) . "\"",
        array_keys($data_attrs),
        array_values($data_attrs)
    ));

    return <<<HTML
<div role="button" onclick="openProductDrawerFromButton(this)" {$data_html} class="mini-product-card-dark block bg-slate-700 rounded-xl shadow-lg overflow-hidden cursor-pointer">
    <div class="mini-product-card-dark__thumb h-32 bg-slate-800">
        <img src="{$img_src}" alt="{$title}" class="w-full h-full object-cover">
    </div>
    <div class="mini-product-card-dark__content p-4 text-white">
        <h5 class="mini-product-card-dark__title text-lg font-black uppercase line-clamp-2 min-h-[2.5em]">{$title}</h5>
        <div class="mini-product-card-dark__price mt-2 flex items-baseline gap-2">
            <span class="mini-product-card-dark__price--current text-lg font-extrabold text-[var(--color-highlight)]">\${$current_price}</span>
            <span class="mini-product-card-dark__price--original text-sm text-gray-400 line-through">
                {$original_price}
            </span>
        </div>
    </div>
</div>
HTML;
}

function renderPlaceholder() {
    return '<div class="mini-product-card-placeholder bg-slate-700 rounded-xl h-full min-h-[200px] flex items-center justify-center text-sm font-semibold text-gray-400 border-2 border-dashed border-slate-600"><span>Próximamente</span></div>';
}

function renderProductCardV2($prod) {
    $is_digital = (($prod['main_section'] ?? '') === 'Productos Digitales') ? 'true' : 'false';
    $icon_map = [
        'Digital' => 'cloud-download', 'Plantilla' => 'layers', 'Impresión' => 'printer',
        'Servicio' => 'megaphone', 'Curso' => 'graduation-cap', 'Programa' => 'trending-up',
        'Recurso' => 'archive',
    ];
    $icon_name = $icon_map[$prod['category'] ?? 'Recurso'] ?? 'archive';

    $is_local = !str_contains($prod['mockup_image'] ?? '', 'http');
    $img_src = $is_local ? ('ia-stock/' . htmlspecialchars($prod['mockup_image'] ?? 'img/default.jpg')) : htmlspecialchars($prod['mockup_image'] ?? 'img/default.jpg');
    
    $title = htmlspecialchars($prod['title']);
    $description_short = htmlspecialchars($prod['description']); 
    $current_price = htmlspecialchars($prod['sale_price'] ?? $prod['price']);
    $original_price_val = isset($prod['sale_price']) ? htmlspecialchars($prod['price']) : null;
    
    $original_price_html = $original_price_val ? "<span class=\"text-2xl text-gray-500 line-through\">\${$original_price_val}</span>" : "";
    $current_price_html = "<span class=\"text-4xl font-extrabold text-[var(--color-highlight)]\">\${$current_price}</span>";
    
    $status_badge = '';
    if (!empty($prod['status']) && $prod['status'] == 'popular') {
        $status_badge = '<span class="absolute top-4 left-4 inline-block px-3 py-1 bg-white text-[var(--color-primary)] text-xs font-bold uppercase rounded-full shadow-lg">Producto Popular</span>';
    } elseif (!empty($prod['status']) && $prod['status'] == 'new') {
         $status_badge = '<span class="absolute top-4 left-4 inline-block px-3 py-1 bg-[var(--color-highlight)] text-[var(--color-primary)] text-xs font-bold uppercase rounded-full shadow-lg">Recien Agregado</span>';
    }

    $sold_units = $prod['sold_units'] ?? 0;
    $sold_units_html = '';
    if ($sold_units > 0) {
        $sold_units_text = ($sold_units > 250) ? '250+' : $sold_units;
        $sold_units_html = <<<HTML
        <div class="flex items-center gap-2 text-gray-400 text-sm font-semibold uppercase">
            <i data-lucide="zap" class="w-4 h-4 text-[var(--color-highlight)]"></i>
            <span class="px-2 py-0.5 bg-red-600 text-white rounded font-bold text-xs">{$sold_units_text}</span>
            <span>Unidades Vendidas</span>
        </div>
HTML;
    }

    $pay_url = "pay.php?product_id=" . htmlspecialchars($prod['id']) . "&price=" . $current_price; 
    $data_attrs = [
        "data-title" => $title,
        "data-description" => $description_short,
        "data-type" => htmlspecialchars($prod['category'] ?? 'Producto'),
        "data-content" => htmlspecialchars($prod['content_type'] ?? 'Activo Digital'),
        "data-price" => '$' . $current_price,
        "data-is-digital" => $is_digital,
        "data-icon-name" => $icon_name,
        "data-pay-url" => $pay_url, 
    ];
    $data_html = implode(' ', array_map(
        fn($k, $v) => "{$k}=\"" . str_replace('"', '&quot;', $v) . "\"",
        array_keys($data_attrs),
        array_values($data_attrs)
    ));

    return <<<HTML
<div class="flex flex-col bg-[var(--color-primary)] rounded-xl shadow-2xl overflow-hidden transition-all duration-300 hover:shadow-black/50 hover:-translate-y-1">
    
    <div class="relative w-full h-48 bg-slate-800">
        <img src="{$img_src}" alt="{$title}" class="w-full h-full object-cover">
        {$status_badge}
    </div>
    
    <div class="p-5 flex flex-col flex-grow">
        <h3 class="text-3xl font-black uppercase text-white leading-tight">{$title}</h3>
        <p class="text-base text-gray-300 mt-2 min-h-[3.5em] line-clamp-3">{$description_short}</p>
        
        <div class="mt-4 flex items-baseline gap-3">
            {$original_price_html}
            {$current_price_html}
        </div>
        
        <div class="mt-3">
            {$sold_units_html}
        </div>

        <button 
            type="button"
            class="w-full bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold p-3 rounded-lg mt-6 flex items-center justify-center gap-2 transition-transform hover:scale-[1.02] hover:brightness-110"
            onclick="openProductDrawerFromButton(this)"
            {$data_html}
        >
            <i data-lucide="shopping-cart" class="w-5 h-5"></i>
            <span>¡LO QUIERO AHORA!</span>
        </button>
    </div>
</div>
HTML;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Productos Impresos <?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>
        .stat-card { 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); }

        .toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 100; pointer-events: none; }
        .toast { 
            transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55); 
            pointer-events: auto; 
            min-width: 320px; 
        }
        .toast.show { opacity: 1; transform: translateX(0); }
        .toast.hide { opacity: 0; transform: translateX(100%); }
        
        .dashboard-banner-v4 {
            background-attachment: local !important; 
            transition: all 0.3s ease;
        }

        .drawer-overlay.open { display: block; }
        .drawer { transform: translateX(100%); transition: transform 0.3s ease-out; z-index: 40; }
        .drawer.open { transform: translateX(0); }

        .mini-product-card-dark { transition: all 0.3s ease; }
        .mini-product-card-dark:hover { transform: translateY(-5px); background: #475569; box-shadow: 0 8px 20px rgba(0,0,0,0.15); }
        
        .section-cta-button {
             transition: all 0.3s ease;
             box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
        }
        .section-cta-button:hover {
            transform: translateY(-2px);
            opacity: 0.95;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2), 0 4px 6px -4px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>

<body data-page-title="Productos Impresos De Todo En Publicidad™"
      data-page-subtitle="Materializa tus ideas con la más alta calidad"
      data-page-icon="printer">

    <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>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            
            <section id="tienda-impresos">
                <div class="mb-8 pb-4 border-b border-gray-300 flex justify-between items-center">
<div class="flex items-center gap-6"> 
                    
                    <div class="flex-shrink-0">
                        <i data-lucide="printer" class="w-20 h-20 text-[var(--color-highlight)]"></i>
                    </div>
                    
                    <div>
                        <h1 class="text-6xl font-black uppercase text-[var(--color-primary)]">Catálogo de Productos</h1>
                        <p class="text-lg font-black text-gray-600 mt-1">Soluciones tangibles para tu marca. Calidad y acabados profesionales.</p>
                    </div>
                </div>
                    
                    <?php if (!empty($client_info['logo_url'])): ?>
                        <div class="hidden lg:block flex-shrink-0 ml-6">
                            <img src="<?php echo htmlspecialchars($client_info['logo_url']); ?>" 
                                 alt="Logotipo de <?php echo htmlspecialchars($client_info['business_name'] ?? 'la empresa'); ?>" 
                                 class="max-h-20 max-w-xs object-contain">
                        </div>
                    <?php endif; ?>
                </div>

                <?php if (empty($productosDeEstaSeccion)): ?>
                    
                    <div class="bg-white p-10 rounded-lg shadow text-center">
                        <i data-lucide="info" class="w-12 h-12 text-[var(--color-highlight)] mx-auto"></i>
                        <h3 class="mt-4 text-2xl font-bold text-gray-800">No hay productos disponibles</h3>
                        <p class="mt-2 text-gray-600">Aún no hemos agregado productos a esta categoría. Vuelve pronto.</p>
                    </div>

                <?php else: ?>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        
                        <?php 
                        foreach ($productosDeEstaSeccion as $producto) {
                            echo renderProductCardV2($producto);
                        }
                        ?>

                    </div>

                <?php endif; ?>

            </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-96 lg: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-3xl font-black uppercase flex-1 text-[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 leading-relaxed"></p>
            <div class="space-y-4 mb-8 p-4 rounded-lg bg-gray-50 border border-gray-200">
                <div class="flex justify-between border-b pb-2">
                    <span class="text-sm font-medium text-gray-500 ">TIPO DE ACTIVO:</span>
                    <span id="drawer-type" class="text-sm font-semibold text-[var(--color-primary)]"></span>
                </div>
                <div class="flex justify-between border-b pb-2">
                    <span class="text-sm font-medium text-gray-500 ">FORMATO/ENTREGA:</span>
                    <span id="drawer-content" class="text-sm font-semibold text-[var(--color-primary)]"></span>
                </div>
                <div class="flex justify-between items-center pt-2">
                    <span class="text-xl font-bold text-gray-700 ">INVERSIÓN:</span>
                    <span id="drawer-price" class="text-2xl font-extrabold  text-[var(--color-secondary)]"></span>
                </div>
            </div>
            <h3 class="text-2xl font-black flex items-center mb-4 text-[var(--color-primary)]">
                <i data-lucide="award" class="w-6 h-6 mr-2 text-[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 ">
                    <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 text-[var(--color-highlight)]"></i>   
                    Derechos de uso profesional y comercial para su negocio.
                </li>
                <li class="flex items-start ">
                    <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 text-[var(--color-highlight)]"></i>   
                    Soporte técnico prioritario sobre la implementación del recurso.
                </li>
                <li class="flex items-start ">
                    <i data-lucide="check" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 text-[var(--color-highlight)]"></i>   
                    Garantía de cumplimiento con los estándares de su mercado.
                </li>
                <li id="drawer-bonus" class="flex items-start ">
                    </li>
            </ul>
        </div>
        <div class="mt-6 pt-4 border-t border-gray-100">
            <a id="drawer-buy-button" href="#" class="w-full text-lg p-3 rounded-xl text-[var(--color-primary)] font-extrabold bg-[var(--color-highlight)] hover:brightness-110 transition flex items-center justify-center gap-2" role="button">
                <i data-lucide="credit-card" class="w-5 h-5 mr-2 inline-block align-text-bottom"></i>   
                ADQUIRIR AHORA
            </a>
            <p id="drawer-delivery-notice" class="text-xs text-center mt-2 text-gray-500 "></p>
        </div>
    </div>
    
    <script>
        // LÓGICA DE WIDGETS (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)
        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');
            const payUrl = button.getAttribute('data-pay-url'); 
            openProductDrawer(title, description, type, content, price, isDigital, iconName, payUrl);
        }
        
        function openProductDrawer(title, description, type, content, price, isDigital, iconName, payUrl) {
            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;

            document.getElementById('drawer-buy-button').setAttribute('href', payUrl); 
            
            const deliveryNotice = document.getElementById('drawer-delivery-notice');
            const bonusItem = document.getElementById('drawer-bonus');
            const iconContainer = document.getElementById('drawer-icon-container');
            const highlightColor = 'white';
            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 = `<li class="flex items-start ">
                    <i data-lucide="download-cloud" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 text-[var(--color-highlight)]"></i>
                    Acceso directo e ilimitado a la descarga en la sección Mi Cuenta.
                    </li>`;
            } else {
                deliveryNotice.innerText = 'Producto impreso. El envío está sujeto a los tiempos de logística (3-5 días).';
                bonusItem.innerHTML = `<li class="flex items-start ">
                    <i data-lucide="truck" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 text-[var(--color-highlight)]"></i>
                    Servicio de seguimiento de envío incluido en la compra.
                    </li>`;
            }
            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();
        }
        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) - (Se mantiene)
        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 bg-white rounded-xl p-3 shadow-2xl flex items-start max-w-xs opacity-0 transform translate-x-full';
            toast.innerHTML = `
                <img src="${sale.image}" alt="Producto ${sale.product}" class="w-12 h-12 object-cover rounded-lg flex-shrink-0 mr-3 shadow-md"/>
                <div class="text-sm flex-1">
                    <p class="font-extrabold text-[var(--color-primary)] text-base leading-tight">${sale.business}</p>
                    <p class="text-gray-700 mt-0.5">
                        <span class="font-semibold">${sale.customer}</span> compró: <span class="font-medium">${sale.product}</span>
                    </p>
                    <div class="flex items-center text-xs mt-1 pt-1 border-t border-gray-100">
                        <i data-lucide="check-circle" class="w-4 h-4 text-green-500 mr-1"></i>
                        <span class="font-medium text-green-600 mr-2">${sale.status}</span>
                        <span class="text-gray-500">• hace ${sale.time} min.</span>
                    </div>
                </div>
            `;
            toastContainer.appendChild(toast);
            lucide.createIcons();   
            toast.offsetWidth;   
            toast.classList.add('show');
            setTimeout(() => {
                toast.classList.remove('show');
                toast.classList.add('hide');
                setTimeout(() => toast.remove(), 500);  
            }, 7000); // DURACIÓN DEL TOAST: 7 segundos
        };

        const startSaleToastLoop = () => {
            if (recentSalesData.length === 0) return;
            let salesIndex = 0;
            const interval = 20000; // INTERVALO ENTRE TOASTS: 20 segundos
            
            // Primer toast 5 segundos después de cargar
            setTimeout(() => showSaleToast(recentSalesData[salesIndex++ % recentSalesData.length]), 5000);   

            // Intervalo para los siguientes
            setInterval(() => {
                const sale = recentSalesData[salesIndex % recentSalesData.length];
                showSaleToast(sale);
                salesIndex++;
            }, interval);
        };
        
        // El contador regresivo no es necesario en esta página, pero lo dejamos
        // por si se reutiliza el JS. No encontrará el ID y no hará nada.
        const startCountdown = () => {
            const countdownEl = document.getElementById("countdown-timer");
            if (!countdownEl) return;
            const endDate = new Date();
            endDate.setDate(endDate.getDate() + <?php echo $daysToOfferEnd ?? 3; ?>);   
            endDate.setHours(23, 59, 59, 999);   
            // ... (resto de la lógica del contador)
        };

        window.onload = function() {
            lucide.createIcons();
            startSaleToastLoop();
            startCountdown(); // Intentará ejecutarse pero no encontrará el elemento
        };

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