<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'dtep/categories.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 = [];

// --- SIMULACIÓN DE DATOS ---
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.', 'price' => 500,
            'category' => 'Impresión', 'mockup_image' => 'img/Manual03.webp', 'stock' => 100, 'sold_units' => 20, 'status' => 'new', 'content_type' => 'Envío Físico',
            'main_section' => 'Productos Impresos'
        ],
        [
            'id' => 4, 'title' => 'Volantes Publicitarios', 'description' => 'Impresión de volantes full color.', 'price' => 800, 'sale_price' => 750,
            'category' => 'Impresión', 'mockup_image' => 'img/Manual03.webp', 'stock' => 100, 'sold_units' => 20, 'status' => 'new', 'content_type' => 'Envío Físico',
            'main_section' => 'Productos Impresos'
        ],
        ['id' => 5, 'title' => 'Servicio de Campaña Ads', 'description' => 'Gestión completa de campañas publicitarias.', 'price' => 1500, 'main_section' => 'Servicios Publicitarios', 'category' => 'Servicio', 'mockup_image' => 'img/bg-servicios.jpg', 'content_type' => 'Consultoría'],
        ['id' => 6, 'title' => 'Consultoría Estratégica', 'description' => 'Sesión de mentoría 1 a 1.', 'price' => 900, 'sale_price' => 850, 'main_section' => 'Servicios Publicitarios', 'category' => 'Servicio', 'mockup_image' => 'img/bg-servicios.jpg', 'content_type' => 'Consultoría'],
        ['id' => 7, 'title' => 'Curso de Marketing IA', 'description' => 'Aprende a usar IA en tu estrategia.', 'price' => 400, 'main_section' => 'Cursos En Linea', 'category' => 'Curso', 'mockup_image' => 'img/bg-cursos.jpg', 'content_type' => 'Acceso a Plataforma'],
        ['id' => 8, 'title' => 'Programa de Crecimiento', 'description' => 'Programa de 6 meses para CEO.', 'price' => 5000, 'main_section' => 'Programas Ejecutivos', 'category' => 'Programa', 'mockup_image' => 'img/bg-programas.jpg', 'content_type' => 'Mentoría Grupal'],
        ['id' => 9, 'title' => 'Kit de Branding', 'description' => 'Recursos para definir tu identidad de marca.', 'price' => 120, 'sale_price' => 100, 'main_section' => 'Productos Digitales', 'category' => 'Recurso', 'mockup_image' => 'https://siteflow.generamasclientes.com/img/SiteFlowLight.webp', 'content_type' => 'Descarga Digital'],
    ];
}

shuffle($todosLosProductos);

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

$seccionesData = [];
foreach ($todosLosProductos as $p) {
    $seccion = $p['main_section'] ?? null;
    if ($seccion) {
        $seccionesData[$seccion][] = $p;
    }
}

$randomImpresos = array_slice(shuffle_and_get($seccionesData['Productos Impresos'] ?? []), 0, 2);
$randomDigitales = array_slice(shuffle_and_get($seccionesData['Productos Digitales'] ?? []), 0, 2);
$randomServicios = array_slice(shuffle_and_get($seccionesData['Servicios Publicitarios'] ?? []), 0, 2);
$randomCursos = array_slice(shuffle_and_get($seccionesData['Cursos En Linea'] ?? []), 0, 2);
$randomProgramas = array_slice(shuffle_and_get($seccionesData['Programas Ejecutivos'] ?? []), 0, 2);

$offerProduct = $todosLosProductos[0];
$offerPrice = $offerProduct['sale_price'] ?? $offerProduct['price'];
$originalPrice = isset($offerProduct['sale_price']) ? $offerProduct['price'] : null;
$daysToOfferEnd = 3;

$customerNames = ["Laura C.", "Jorge G.", "Ana M.", "Carlos R.", "Sofía P.", "Juan V.", "María L."];
$recentSales = [];
$company_name = $company_name_from_db; // Usar el nombre de la compañía
$statuses = ["Compra Confirmada", "Procesando Pago", "Listo para Envío"];

if (!empty($todosLosProductos)) {
    for ($i = 0; $i < 7; $i++) {
        $product = $todosLosProductos[array_rand($todosLosProductos)];
        // Determinar la URL de la imagen (usando mockup_image o una predeterminada)
        $img_url = htmlspecialchars($product['mockup_image'] ?? 'img/default.jpg');
        // Adaptar la ruta si es local y no absoluta
        if (!str_contains($img_url, 'http') && !str_starts_with($img_url, '/')) {
             $img_url = 'ia-stock/' . $img_url; // Asume 'ia-stock' es el prefijo si es local
        }
        
        $recentSales[] = [
            'customer' => $customerNames[array_rand($customerNames)],
            'product' => htmlspecialchars($product['title']),
            'time' => rand(1, 15),
            'image' => $img_url, // Nueva propiedad
            'business' => htmlspecialchars($company_name), // Nueva propiedad
            'status' => $statuses[array_rand($statuses)] // Nueva propiedad
        ];
    }
}

function renderMiniProductCard($prod, $seccionName) {
    // Determine the product type for dynamic content in the drawer
    $is_digital = (($prod['main_section'] ?? '') === 'Productos Digitales') ? 'true' : 'false';

    // Icono basado en la categoría (se puede mejorar si se añade un campo 'icon' al producto)
    $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 ? ('img' . 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 = isset($prod['sale_price']) ? htmlspecialchars($prod['price']) : null;
    $pay_url = "pay.php?product_id=" . htmlspecialchars($prod['id']) . "&price=" . $current_price; 

    // Prepara los data-attributes para el Drawer
    $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>';
}

?>
<!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>
        .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); }

        /* Estilo de Toast ACTUALIZADO */
        .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; /* Asegura espacio para todo el contenido */
        }
        .toast.show { opacity: 1; transform: translateX(0); }
        .toast.hide { opacity: 0; transform: translateX(100%); }
        
        /* CORRECCIÓN: Estilo para restaurar el fondo de la tarjeta de sección */
        .dashboard-banner-v4 {
            background-attachment: local !important; 
            transition: all 0.3s ease;
        }

        .daily-deal-mockup-layout { transition: all 0.3s ease; }
        .daily-deal-mockup-layout:hover { transform: scale(1.005); }
        .mockup-image-container img { transition: opacity 0.3s ease, transform 0.3s ease; }
        .daily-deal-mockup-layout:hover .mockup-image-container img { opacity: 1; transform: scale(1.05); }

        @media (max-width: 768px) {
            .daily-deal-mockup-layout { flex-direction: column; min-height: auto; }
            .mockup-image-container { flex-basis: auto; min-height: 200px; }
            .offer-details-container { flex-basis: auto; padding: 1.5rem; }
            .product-title-offer { font-size: 1.75rem; }
            .price-timer-wrapper { flex-direction: column; align-items: center; gap: 1rem; margin-bottom: 1rem; }
            .price-info-offer { align-items: center; }
            .price-regular-offer { text-align: center; }
            #daily-deal #countdown-timer { font-size: 1.5rem; align-self: center; width: 100%; justify-content: center; }
            .offer-cta-button { font-size: 1rem; }
        }
        
        .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); }
        
        /* Estilo para los botones de sección actualizados */
        .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="Bienvenido A De Todo En Publicidad™"
      data-page-subtitle="Tu Aliado De Recursos Y Activos Para Promoción"
      data-page-icon="shopping-bag"
      class=" bg-gray-100">

    <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 space-y-12">
            
            <section id="daily-deal" class="p-0 shadow-none">
    <div class="flex flex-col md:flex-row bg-[var(--color-primary)] rounded-2xl overflow-hidden shadow-2xl shadow-black/50 min-h-[400px] text-white transition-all hover:shadow-black/70">
        
        <div class="offer-details-container flex-grow p-6 md:p-10 lg:p-12 flex flex-col justify-center md:w-3/5 relative z-10">
            
            
            <h4 class="product-title-offer text-4xl md:text-7xl font-black uppercase leading-tight mt-1 text-white">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full font-bold text-xs uppercase tracking-widest bg-[var(--color-highlight)] text-slate-900 shadow-md">
                   <i data-lucide="zap" class="w-4 h-4"></i> OFERTA RELÁMPAGO DEL DÍA
                </span><br />
                <?php echo htmlspecialchars($offerProduct['title']); ?>
            </h4>

            <div class="mt-6 mb-6 flex items-end gap-6">
                <div class="price-info-offer flex flex-col items-start flex-shrink-0">
                    <p class="current-price-offer text-5xl md:text-6xl font-black leading-none text-[var(--color-highlight)] drop-shadow-lg">$<?php echo htmlspecialchars($offerPrice); ?></p>
                </div>
                <?php if ($originalPrice): ?>
                    <div class="flex flex-col items-start">
                            <span class="text-lg text-gray-500 font-black uppercase whitespace-nowrap">Precio Regular</span>
                            <p class="price-regular-offer text-2xl line-through text-gray-400 opacity-80">$<?php echo htmlspecialchars($originalPrice); ?></p>
                    </div>
                <?php endif; ?>
            </div>

            <div class="w-full max-w-xs md:max-w-sm">    
                <?php    
                    $offerDataAttrs["data-is-digital"] = (($offerProduct['main_section'] ?? '') === 'Productos Digitales') ? 'true' : 'false';
                    // Agregando data-attributes necesarios para que el drawer funcione
                    $offerDataAttrs["data-title"] = htmlspecialchars($offerProduct['title']);
                    $offerDataAttrs["data-description"] = htmlspecialchars($offerProduct['description']);
                    $offerDataAttrs["data-type"] = htmlspecialchars($offerProduct['category'] ?? 'Producto');
                    $offerDataAttrs["data-content"] = htmlspecialchars($offerProduct['content_type'] ?? 'Activo Digital');
                    $offerDataAttrs["data-price"] = '$' . htmlspecialchars($offerPrice);
                    $offerDataAttrs["data-icon-name"] = 'zap';
                    // NUEVO: URL de pago para el botón
                    $offerDataAttrs["data-pay-url"] = "pay.php?product_id=" . htmlspecialchars($offerProduct['id']) . "&price=" . htmlspecialchars($offerPrice);


                    $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 offer-cta-button w-full py-4 bg-[var(--color-highlight)] text-[var(--color-secondary)] font-black rounded-xl hover:scale-[1.01] hover:shadow-2xl hover:shadow-[var(--color-highlight)]/50 transition flex items-center justify-center gap-2 text-xl"
                        onclick="openProductDrawerFromButton(this)"
                        <?php echo $offerDataHtml; ?>
                >
                    <i data-lucide="shopping-cart" class="w-6 h-6"></i> ¡ADQUIRIRLO YA!    
                </button>

                <div class="mt-3 text-sm text-gray-300 font-semibold uppercase flex items-center gap-2">
                    <i data-lucide="megaphone" class="w-4 h-4 text-green-400"></i>
                    <span>
                        Más de <span class="text-lg font-black text-white"><?php echo $offerProduct['sold_units'] ?? rand(50, 150); ?></span> unidades vendidas
                    </span>
                </div>
            </div>
        </div>
        
        <div class="mockup-image-container flex-shrink-0 w-full md:w-2/5 min-h-[300px] md:min-h-auto relative overflow-hidden flex flex-col items-center justify-center bg-transparent p-4 md:p-8">
            
            <img src="https://siteflow.generamasclientes.com/img/SiteFlowLight.webp" 
                 alt="<?php echo htmlspecialchars($offerProduct['title']); ?> Mockup" 
                 class="w-full max-h-[70%] object-contain p-4 transition-transform duration-500 hover:scale-[1.05]"/>
                        
            <div class="w-full mt-6 flex flex-col items-center">
                <p class="text-lg font-black uppercase text-gray-300 mb-2 text-center">¡ESTA OFERTA TERMINA EN!</p>
                <div id="countdown-timer" class="flex items-center gap-4 p-3 bg-black/50 rounded-xl shadow-2xl text-[var(--color-highlight)] text-xl font-black w-full justify-center">
                    <span id="hours" class="min-w-[45px] text-center"><div class="time-label text-xs font-medium text-gray-400">HRS</div></span>
                    <span>:</span>
                    <span id="minutes" class="min-w-[45px] text-center"><div class="time-label text-xs font-medium text-gray-400">MIN</div></span>
                    <span>:</span>
                    <span id="seconds" class="min-w-[45px] text-center"><div class="time-label text-xs font-medium text-gray-400">SEG</div></span>
                </div>
            </div>
        </div>
    </div>
</section>
            
<section id="dashboard-navegacion" class="mt-12">
    <div class="flex flex-col gap-6">

        <?php
        $sections_map = [
            'Productos Impresos' => ['var' => $randomImpresos, 'desc' => 'Materializa tus ideas con la más alta calidad y acabado profesional para tu marca.', 'link' => 'store-printed-products.php', 'bg' => 'Store01.webp', 'icon' => 'printer'],
            'Productos Digitales' => ['var' => $randomDigitales, 'desc' => 'Descargas instantáneas y recursos listos para potenciar tu presencia en línea.', 'link' => 'store-digital-products.php', 'bg' => 'Store02.webp', 'icon' => 'cloud-download'],
            'Servicios Publicitarios' => ['var' => $randomServicios, 'desc' => 'Estrategias y gestión experta para amplificar tu mensaje y alcanzar más clientes.', 'link' => 'store-services-products.php.php', 'bg' => 'Store03.webp', 'icon' => 'megaphone'],
            'Cursos En Linea' => ['var' => $randomCursos, 'desc' => 'Domina nuevas habilidades y metodologías con nuestros programas de aprendizaje.', 'link' => 'store-courses-products.php', 'bg' => 'Store04.webp', 'icon' => 'graduation-cap'],
            'Programas Ejecutivos' => ['var' => $randomProgramas, 'desc' => 'Mentoría personalizada y soluciones de élite para el crecimiento exponencial de tu empresa.', 'link' => 'store-programs-products.php', 'bg' => 'Store05.webp', 'icon' => 'trending-up'],
        ];

        foreach ($sections_map as $title => $data):
            $randomProducts = $data['var'];
            $bg_url = 'dtep/' . htmlspecialchars($data['bg']); 
        ?>
        
        <div class="dashboard-banner-v4 flex flex-col lg:flex-row w-full relative bg-[var(--color-primary)] border border-slate-700 rounded-xl shadow-2xl overflow-hidden text-white bg-cover bg-center" style="background-image: url('<?php echo $bg_url; ?>');">
            
            <div class="banner-v4__info relative z-20 flex-shrink-0 w-full lg:w-1/2 p-6 md:p-10 flex flex-col justify-center text-center lg:text-left items-center lg:items-start">
                <h4 class="banner-v4__title text-4xl font-black uppercase leading-tight mb-2 text-white"><?php echo htmlspecialchars($title); ?></h4>
                <p class="banner-v4__desc text-gray-300 mb-6 max-w-xl mx-auto lg:mx-0"><?php echo htmlspecialchars($data['desc']); ?></p>
                
                <a href="<?php echo htmlspecialchars($data['link']); ?>"    
                    class="section-cta-button inline-flex items-center justify-center font-extrabold 
                           lg:w-auto mx-auto lg:mx-0                       
                           bg-[var(--color-highlight)] text-[var(--color-primary)] rounded-lg py-3 px-6 
                           hover:brightness-110 text-sm uppercase tracking-wider">
                    <i data-lucide="<?php echo htmlspecialchars($data['icon']); ?>" class="w-5 h-5 mr-3"></i>
                    Ver Catálogo de <?php echo str_replace(['Productos ', ' En Linea', 's'], ['', '', ''], $title); ?>
                </a>
            </div>
            
            <div class="banner-v4__products relative z-20 flex-shrink-0 w-full lg:w-1/2 p-6 md:p-10 grid grid-cols-2 gap-4">
                <?php 
                $count = 0;
                foreach ($randomProducts as $prod) {
                    echo renderMiniProductCard($prod, $title);
                    $count++;
                }
                if ($count < 2) {
                    for ($i = $count; $i < 2; $i++) {
                        echo renderPlaceholder();
                    }
                }
                ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</section>
            
            <hr class="my-12 border-gray-300">

            <section class="custom-order-section bg-[var(--color-primary)] text-white p-6 md:p-10 rounded-2xl shadow-xl shadow-slate-900/30 grid grid-cols-1 lg:grid-cols-[1fr_1.5fr] gap-8 items-center">
                <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 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-400"></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-400"></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-400"></i>
                            <span class="text-lg font-bold">Entrega garantizada y soporte de expertos.</span>
                        </li>
                    </ul>
                </div>
                <form class="custom-order-form bg-black/30 p-6 rounded-xl shadow-inner backdrop-blur-sm" method="POST" action="send_order.php">
                    <h3 class="text-xl font-bold mb-4 flex items-center gap-2"><i data-lucide="send" class="w-5 h-5 mr-2 text-[var(--color-highlight)]"></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 Nombre Completo</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> ¡SÍ, QUIERO ALGO PERSONALIZADO!
                    </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-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 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 (ACTUALIZADA con data-pay-url)
        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'); // NUEVO: Obtiene la URL de pago
            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;

            // NUEVO: Asigna la URL de pago al botón de compra (ahora un enlace <a>)
            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'; // Icon color inside primary background
            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) Y CONTADOR REGRESIVO (OFERTA) (ACTUALIZADO)
        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');
            // Usando clases de Tailwind para apariencia y la clase .toast custom para la animación
            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);
        };

        const startCountdown = () => {
            const countdownEl = document.getElementById("countdown-timer");
            if (!countdownEl) return;
            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;
                if (distance < 0) {
                    clearInterval(timer);
                    countdownEl.innerHTML = "<span class='text-red-500 font-extrabold text-lg'>¡LA OFERTA HA EXPIRADO!</span>";
                    const offerButton = document.querySelector('#daily-deal button');
                    if (offerButton) offerButton.disabled = true;
                    return;
                }
                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');
                
                // Mantiene la estructura original del HTML para los spans
                document.getElementById("hours").innerHTML = formatTime(hours + (days * 24)) + '<div class="time-label text-xs font-medium text-gray-400">HRS</div>';
                document.getElementById("minutes").innerHTML = formatTime(minutes) + '<div class="time-label text-xs font-medium text-gray-400">MIN</div>';
                document.getElementById("seconds").innerHTML = formatTime(seconds) + '<div class="time-label text-xs font-medium text-gray-400">SEG</div>';
            }, 1000);
        };

        window.onload = function() {
            lucide.createIcons();
            startSaleToastLoop();
            startCountdown();
        };

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