<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

$db_error_message = null;

try {
    $stmt = $pdo->query("SELECT * FROM website_config WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $company_name_from_db       = htmlspecialchars($config['company_name'] ?? 'Nombre de la Empresa');
        $contact_phone_from_db      = htmlspecialchars($config['phone_primary'] ?? '');
        $website_url_from_db        = htmlspecialchars($config['website_url'] ?? '');
        $value_proposition_from_db  = htmlspecialchars($config['value_proposition'] ?? '');
    } else {
        $company_name_from_db = 'Nombre de la Empresa';
        $contact_phone_from_db = '';
        $website_url_from_db = '';
        $value_proposition_from_db = '';
        $db_error_message = 'No se encontró la configuración. Se usarán valores por defecto.';
    }
} catch (PDOException $e) {
    error_log("Error PDO al cargar configuración web: " . $e->getMessage());
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_phone_from_db = '';
    $website_url_from_db = '';
    $value_proposition_from_db = '';
    $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());
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_phone_from_db = '';
    $website_url_from_db = '';
    $value_proposition_from_db = '';
    $db_error_message = 'Error inesperado al cargar configuración: ' . $e->getMessage();
}
ob_end_clean();

require_once 'ia-stock/store-products.php';

shuffle($todosLosProductos);

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

$categoryCounts = [];
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);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Tienda IAStock™ De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <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>
        /* COMENTARIO: Paleta de Colores - Variables obligatorias (Punto 2) */
        :root { --color-primary: #07162d; --color-secondary: #9e1428; --color-highlight: #ffc857; --color-background: #f5f5f5; }
        /* COMENTARIO: Tipografía - Fuente Barlow (Punto 1) */
        body { font-family: 'Barlow', sans-serif; background-color: var(--color-background); }
        .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; }

        /* COMENTARIO: Estilo de Tarjeta - Incluye sombra y transición de hover/transformación (Punto 1) */
        .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;
        }
        .asset-card__content .price-container {
            display: flex;
            align-items: baseline;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        .asset-card__content .price-container .current-price {
            /* COMENTARIO: Color de Resalte para el precio (Punto 2) */
            font-weight: 800;
            font-size: 1.5rem;
            color: var(--color-highlight);
            line-height: 1;
        }
        .asset-card__content .price-container .original-price {
            font-size: 1rem;
            color: #6b7280;
            text-decoration: line-through;
        }

        .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;
        }

        /* ESTILO NUEVO PARA UNIDADES VENDIDAS */
        .asset-card__sales {
            font-size: 0.8rem;
            color: #d1d5db;
            margin-top: 0.5rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        .asset-card__sales svg {
            width: 1rem;
            height: 1rem;
            color: #a3a3a3;
        }

        /* COMENTARIO: Estilo de Botón - Incluye transición de hover/transformación (Punto 1) */
        .asset-card__btn {
            display: inline-flex;
            gap: .5rem;
            align-items: center;
            justify-content: center;
            padding: .65rem 1rem;
            border-radius: 10px;
            /* Usa var(--color-highlight) como fondo principal (Punto 2) */
            background: var(--color-highlight);
            color: var(--color-primary);
            font-weight: 700;
            transition: all .2s ease;
            border: none; /* Asegurar que sea un botón sin borde */
            text-decoration: none;
            width: 100%;
            margin-top: 1rem;
            cursor: pointer;
        }
        .asset-card__btn:hover { opacity: .9; transform: scale(1.02); }
        .asset-card__btn svg { width: 18px; height: 18px; }

        /* COMENTARIO: Estilo para el botón de compra principal del Drawer */
        .btn-secondary {
            background-color: var(--color-secondary); /* Color Secundario (Acento) (Punto 2) */
            box-shadow: 0 4px 6px -1px rgba(158, 20, 40, 0.1), 0 2px 4px -2px rgba(158, 20, 40, 0.06);
            transition: all .2s ease;
            border: none;
            font-family: 'Barlow', sans-serif;
        }

        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(158, 20, 40, 0.2), 0 4px 6px -4px rgba(158, 20, 40, 0.1);
            opacity: 0.95;
        }

        /* COMENTARIO: Estilo para el Modal/Drawer de detalles (Tailwind + Custom CSS) */
        #product-drawer {
            transform: translateX(100%);
            transition: transform 0.3s ease-out;
            z-index: 50;
        }
        #product-drawer.open {
            transform: translateX(0);
        }
        #product-drawer-overlay.open {
            display: block;
        }

        .pill { display: inline-flex; gap: .35rem; align-items: center; border-radius: 999px; font-weight: 700; text-transform: uppercase; font-size: .7rem; padding: .35rem .6rem; letter-spacing: .4px; }
        .pill--new { background: #dcfce7; color: #166534; }
        .pill--hot { background: #fee2e2; color: #991b1b; }
        .pill--updated { background: #dbeafe; color: #1e40af; }
        .pill--premium { background: #fffbeb; color: #b45309; }
        
        .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.25rem; font-weight: 800; color: #111827; line-height: 1; margin-bottom: 0.5rem; }
        .stat-card__label { font-size: 0.9rem; font-weight: 600; color: #4b5563; line-height: 1.2; }

        .custom-order-section {
            background: linear-gradient(180deg, #1f2937, var(--color-primary)); /* Color Primary de Base Oscura (Punto 2) */
            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;
            }
        }
        
        .cta-text {
            text-align: center;
            padding: 1rem;
        }

        @media (min-width: 768px) {
            .cta-text {
                text-align: left;
                padding: 0;
            }
        }

        .cta-text h2 {
            font-size: 2.5rem;
            font-weight: 800;
            line-height: 1.2;
            margin-bottom: 1rem;
        }

        .cta-text p {
            font-size: 1.125rem;
            color: #d1d5db;
        }

        .custom-order-form {
            background: #111827;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.2);
        }

        .custom-order-form label {
            color: #cbd5e1;
            font-weight: 600;
        }

        .custom-order-form input,
        .custom-order-form textarea {
            /* COMENTARIO: Asegura que el color de fondo sea el correcto para mantener contraste */
            background-color: #F5F5F5;
            border-color: #334155;
            color: #07162d; /* Texto de formulario oscuro */
        }
    </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="#ia-stock-latest" 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="shopping-cart" class="w-5 h-5"></i> EXPLORAR AHORA
                </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-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): ?>
            <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 (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"><?php echo htmlspecialchars($producto['title']); ?></h4>
                        <p class="asset-card__desc"><?php echo htmlspecialchars($producto['description']); ?></p>
                    </div>
                    
                                        <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>

                    <?php if (isset($producto['sold_units'])): ?>
                        <div class="asset-card__sales">
                            <i data-lucide="zap"></i>
                            <span class="text-[var(--color-highlight)] font-bold"><?php echo htmlspecialchars($producto['sold_units']); ?>+</span>
                            <span class="text-gray-400">VENDIDOS</span>
                        </div>
                    <?php endif; ?>
                    
                    <?php
                        // COMENTARIO: Lógica PHP para preparar los data-atributos para el modal JS
                        $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'; 

                        // COMENTARIO: Mapeo de Categoría a Icono Lucide (Punto 4)
                        $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 mt-4 w-full py-3 bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold rounded-lg hover:brightness-110 hover:shadow-xl transition flex items-center justify-center gap-2 tool-card"
                        onclick="openProductDrawerFromButton(this)"
                        <?php echo $dataHtml; ?>
                    >
                        <i data-lucide="shopping-cart"></i> COMPRAR 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
        </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>
    
    </div>

    <script>
        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;

            // COMENTARIO: Función para generar HTML de Tarjeta de Producto (compatible con la carga de más)
            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';
                
                // COMENTARIO: Lógica de Iconografía y Datos para el Modal (Punto 4)
                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',
                }[productCategory] || 'image'; // Default a '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">${finalPrice}</span>` :
                    `<span class="current-price">${finalPrice}</span>`;
                
                // COMENTARIO: Los data-atributos se usan para pasar los datos al modal (Punto 1)
                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}"
                `;

                return `
                <article class="asset-card">
                    <div class="asset-card__thumbnail">
                        <img src="${mockupPath}" alt="Mockup de ${product.title}">
                        <span class="asset-card__tag ${statusClass}">
                            ${statusText}
                        </span>
                    </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="price-container">
                            ${priceHTML}
                        </div>
                        ${product.sold_units ? 
                            `<div class="asset-card__sales">
                                <i data-lucide="zap"></i>
                                <span class="text-[var(--color-highlight)] font-bold">${product.sold_units}+</span>
                                <span class="text-gray-400">VENDIDOS</span>
                            </div>` : ''}
                                                <button type="button"
                            class="asset-card__btn"
                            onclick="openProductDrawerFromButton(this)"
                            ${dataAttrs}
                        >
                            <i data-lucide="shopping-cart"></i> COMPRAR 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++;
                    loadMoreBtn.textContent = 'CARGAR MÁS PRODUCTOS';
                    loadMoreBtn.disabled = false;

                    if ((currentPage * itemsPerPage) >= allProductsData.length) {
                        loadMoreBtn.style.display = 'none';
                    }
                }, 400);
            });
        });
    </script>
    
    <script>
document.addEventListener('DOMContentLoaded', () => {

    // Función principal que maneja el ocultamiento, la reaparición y el Local Storage
    const toggleWidgetVisibility = (widgetId, isHidden) => {
        const widget = document.getElementById(widgetId);
        // Encuentra el contenedor del botón de mostrar usando el data-widget-id
        const showContainer = document.querySelector(`.show-widget-container [data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
        const videoPlayer = widget ? widget.querySelector('video') : null;

        if (!widget || !showContainer) return; // Se detiene si no encuentra los elementos

        if (isHidden) {
            // Acción para OCULTAR
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            // IMPORTANTE: Detiene el video para ahorrar recursos
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            // Acción para MOSTRAR
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }

        // Guarda la preferencia en Local Storage, individualmente para cada widget
        localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
    };

    // 1. Configurar los botones de OCULTAR (clase: hide-widget-btn)
    document.querySelectorAll('.hide-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a ocultar
            toggleWidgetVisibility(widgetId, true); 
        });
    });

    // 2. Configurar los botones de MOSTRAR (clase: show-widget-btn)
    document.querySelectorAll('.show-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a mostrar
            toggleWidgetVisibility(widgetId, false); 
        });
    });

    // 3. Comprobar y aplicar el estado guardado al cargar la página para TODOS los widgets
    document.querySelectorAll('.video-widget').forEach(widget => {
        const widgetId = widget.id;
        const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
        if (isHidden) {
            // Si el usuario lo ocultó antes, se aplica el estado de oculto
            toggleWidgetVisibility(widgetId, true);
        }
    });
});

        // COMENTARIO: Nueva función para leer los atributos del botón y pasar al modal
        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'; // Iconos dentro de fondo Primary deben ser blancos

            // Insertar el ícono dinámico en el encabezado del drawer (Punto 4)
            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.';
                // COMENTARIO: ICONOGRAFÍA - Lucide con color de Resalte (Punto 2)
                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).';
                // COMENTARIO: ICONOGRAFÍA - Lucide con color de Resalte (Punto 2)
                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');
            
            // Re-renderizar íconos de Lucide
            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); 
        }
        
        window.onload = function() {
            lucide.createIcons();
        };

</script>

</body>
</html>