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

// --- Tu código de conexión a la base de datos ---
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');
    } else {
        $company_name_from_db = 'Nombre de la Empresa';
    }
} catch (Exception $e) {
    $company_name_from_db = 'Nombre de la Empresa';
}
ob_end_clean();
// --- Fin de la conexión ---

shuffle($todasLasPlantillas);

$initialTemplatesToShow = 8;
$plantillasIniciales = array_slice($todasLasPlantillas, 0, $initialTemplatesToShow);
$totalTemplates      = count($todasLasPlantillas);

// Obtener categorías únicas para los botones de filtro
$categories = array_unique(array_column($todasLasPlantillas, 'category'));
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Stock Plantillas <?php echo htmlspecialchars($branding['iastock_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">

    <style>
        .hero-image-overlay { position: relative; background-size: cover; background-position: center; border-radius: 12px; height: 250px; overflow: hidden; display: flex; align-items: center; justify-content: center; }
        .hero-image-overlay::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); }
        .overlay-text { position: relative; z-index: 10; }
        .template-card { background: #ffffff; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; transition: all .2s ease; box-shadow: 0 6px 14px -8px rgba(2,6,23,.25); }
        .template-card:hover { transform: translateY(-6px); box-shadow: 0 18px 28px -14px rgba(2,6,23,.35); }
        .template-card__thumbnail{ position:relative; background:#eef2f7; aspect-ratio: 4/3; overflow:hidden; }
        .template-card__thumbnail img{ width:100%; height:100%; object-fit:cover; display:block; opacity:0; transition:opacity .25s ease, transform .35s ease; }
        .template-card.loaded .template-card__thumbnail img{ opacity:1; }
        .template-card:hover .template-card__thumbnail img{ transform:scale(1.03); }
        .thumb-skeleton{ position:absolute; inset:0; background: linear-gradient(90deg,#eef2f7 25%, #f5f7fb 37%, #eef2f7 63%); background-size:400% 100%; animation: shimmer 1.2s infinite; }
        @keyframes shimmer{ 0%{background-position:100% 0} 100%{background-position:0 0} }
        .template-card__content { padding: .8rem 1rem; display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; border-top: 1px solid #eef2f7; }
        .info-pill { display: inline-flex; align-items: center; gap: .4rem; padding: .28rem .6rem; border-radius: 999px; font-size: .74rem; font-weight: 800; }
        .pill--category { background: #f3f4f6; color: #374151; }
        .pill--id { background: #e0e7ff; color: #3730a3; }
        .template-card__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .7rem; padding: 0 1rem 1rem; margin-top: auto; padding-top: .5rem; }
        .template-card__btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; padding: .6rem 1rem; border-radius: 10px; font-weight: 700; text-decoration: none; transition: .2s ease; font-size: .9rem; }
        .template-card__btn--view { background: #f3f4f6; color: #111827; border: 1px solid #e5e7eb; }
        .template-card__btn--view:hover { background: #e7eaf0; }
        .template-card__btn--download { background: var(--color-primary); color: #fff; }
        .template-card__btn--download:hover { filter: brightness(.95); }
        #modal { position: fixed; inset: 0; background: rgba(0, 0, 0, .8); z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 1rem; backdrop-filter: blur(5px); opacity: 0; visibility: hidden; transition: opacity .25s ease, visibility .25s ease; }
        #modal.show { opacity: 1; visibility: visible; }
        .modal-content { background: #000; border-radius: 16px; padding: 0; width: min(100%, 1080px); max-height: 90vh; display: flex; flex-direction: column; overflow: hidden; }
        .modal-header { display: flex; align-items: center; justify-content: space-between; padding: .85rem 1rem; border-bottom: 1px solid rgba(255,255,255,.1); background: #111; color: #fff; }
        .modal-title { font-weight: 800; font-size: 1rem; color: #fff; }
        .modal-actions { display: flex; align-items: center; gap: .5rem; }
        .modal-actions a { display: inline-flex; align-items: center; gap: .4rem; background: #fff; color: #0f172a; padding: .5rem .8rem; border-radius: 8px; font-weight: 800; text-decoration: none; transition: .2s ease; }
        .modal-actions a:hover { background: #f3f4f6; }
        .modal-close-btn { background: transparent; color: #fff; border: none; padding: 0.4rem 0.55rem; display: flex; align-items: center; justify-content: center; cursor: pointer; opacity: .8; transition: opacity .2s ease; }
        .modal-close-btn:hover { opacity: 1; }
        .modal-image-container { background: black; display: flex; align-items: center; justify-content: center; padding: 1rem; }
        .modal-image-container img { max-width: 100%; max-height: 80vh; object-fit: contain; }
        #template-grid-container { margin-top: 2rem; }

        /* --- ESTILOS PARA FILTROS (ESTRUCTURA DE IMÁGENES) --- */
        .filter-controls { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; justify-content: space-between; margin-bottom: 2rem; padding: 1rem; background-color: #f9fafb; border-radius: 12px; border: 1px solid #e5e7eb; }
        .search-wrapper { position: relative; flex-grow: 1; }
        #search-input { width: 100%; padding: .75rem 1rem .75rem 2.5rem; border-radius: 8px; border: 1px solid #d1d5db; font-weight: 500; transition: all .2s; }
        #search-input:focus { outline: none; border-color: var(--color-primary); box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3); }
        .search-wrapper .icon { position: absolute; top: 50%; left: .8rem; transform: translateY(-50%); color: #6b7280; }
        .category-filters { display: flex; flex-wrap: wrap; gap: .5rem; background: #e5e7eb; padding: .3rem; border-radius: 8px; }
        .category-filters button { padding: .5rem 1rem; border: none; background: transparent; border-radius: 6px; font-weight: 700; cursor: pointer; transition: all .2s; color: #374151; }
        .category-filters button.active { background: #ffffff; color: var(--color-primary); box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        #no-results-message { display: none; text-align: center; padding: 3rem 1rem; background-color: #f9fafb; border-radius: 12px; }
    </style>

    <script src="files/header-manager.js"></script>
</head>
<body
    data-page-title="Plantillas Para Negocios de Limpieza"
    data-page-subtitle="Recursos de plantillas para potenciar tu marca"
    data-page-icon="layout-template">
    
   <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>
    <?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="bienvenida-ia-stock" class="p-0">
                <div class="relative overflow-hidden rounded-2xl md:rounded-3xl bg-gradient-to-br from-[var(--color-primary)] via-[#0b2242] to-[#07162d] text-white">
                    <div class="absolute -top-24 -left-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[var(--color-secondary)]"></div>
                    <div class="absolute -bottom-24 -right-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[var(--color-highlight)]"></div>
                    <div class="relative p-6 md:p-10">
                        <div class="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="sparkles" class="w-4 h-4"></i><span class="text-xs tracking-wide uppercase font-semibold">Contenido para tu Negocio</span></div>
                                <h1 class="text-3xl md:text-4xl font-extrabold leading-tight tracking-tight"><span class="text-[var(--color-highlight)]">Plantillas Estratégicas</span> <br />Para Impulsar Tu Negocio</h1>
                                <p class="text-white/80 mt-4 max-w-2xl text-base md:text-lg">Ahorra tiempo y encuentra plantillas profesionales listas para usar en tus anuncios y redes sociales.</p>
                                <div class="mt-6 flex flex-wrap gap-3"><a href="#template-grid" 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="layout-template" class="w-5 h-5"></i> EXPLORAR PLANTILLAS</a></div>
                            </div>
                            <div class="hidden lg:block">
                                <div class="hero-image-overlay" style="background-image: url('/ia-stock/videos/thumbnails/limpieza-stock-01.jpg');">
                                    <div class="overlay-text text-center text-white p-4">
                                        <div class="flex items-center justify-center space-x-2"><i data-lucide="gem" class="w-12 h-12 text-white drop-shadow-lg"></i><p class="text-6xl md:text-7xl font-extrabold drop-shadow-lg text-white"><?php echo $totalTemplates; ?></p></div>
                                        <p class="text-sm uppercase font-semibold tracking-wider" style="color: var(--color-highlight);">Plantillas Disponibles</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            
            <section id="filter-section" class="mt-8">
                <div class="filter-controls">
                    <div class="search-wrapper">
                        <i data-lucide="search" class="icon w-5 h-5"></i>
                        <input type="search" id="search-input" placeholder="Buscar Por ID (ej: TPL001)">
                    </div>
                    <div class="category-filters" id="category-filter-buttons">
                        <button type="button" data-filter="all" class="active">TODOS</button>
                        <?php foreach ($categories as $category): ?>
                            <button type="button" data-filter="<?php echo htmlspecialchars($category); ?>"><?php echo htmlspecialchars($category); ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>

            <section id="template-grid-container">
                <div id="template-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <?php foreach ($plantillasIniciales as $template): ?>
                        <?php
                            $id = htmlspecialchars($template['id']);
                            $templateUrl = htmlspecialchars($template['filename']);
                            $category = htmlspecialchars($template['category']);
                            $title = htmlspecialchars($template['title']);
                            $mockupPath = 'ia-stock/' . htmlspecialchars($template['mockup_image']);
                        ?>
                        <article class="template-card" 
                                 data-template-url="<?php echo $templateUrl; ?>" 
                                 data-category="<?php echo $category; ?>" 
                                 data-title="<?php echo $title; ?>" 
                                 data-mockup="<?php echo $mockupPath; ?>" 
                                 data-id="<?php echo $id; ?>">
                            <div class="template-card__thumbnail">
                                <div class="thumb-skeleton" aria-hidden="true"></div>
                                <img src="<?php echo $mockupPath; ?>" alt="Maqueta de <?php echo $title; ?>" loading="lazy" onerror="this.onerror=null;this.src='https://placehold.co/640x480/eef2f7/9aa4b2?text=Plantilla';">
                            </div>
                            <div class="template-card__content">
                                <span class="info-pill pill--id"><i data-lucide="asterisk"></i><?php echo $id; ?></span>
                                <span class="info-pill pill--category"><i data-lucide="folder"></i><?php echo $category; ?></span>
                            </div>
                            <div class="template-card__actions">
                                <button type="button" class="template-card__btn template-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                                <a href="<?php echo $templateUrl; ?>" target="_blank" class="template-card__btn template-card__btn--download"><i data-lucide="edit-3" class="w-4 h-4"></i> USAR</a>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>

                <div id="no-results-message" class="hidden mt-8">
                    <h3 class="text-xl font-bold text-gray-700">NO SE ENCONTRARON RESULTADOS</h3>
                    <p class="text-gray-500 mt-2">Intenta Ajustar Tu Búsqueda O Filtros</p>
                </div>
                <div id="load-more-container" class="flex justify-center mt-12">
                    <button id="load-more-btn" class="bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold py-3 px-8 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2">
                        <i data-lucide="plus-circle" class="w-5 h-5"></i>
                        <span>CARGAR MÁS PLANTILLAS</span>
                    </button>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="modal" class="fixed inset-0 z-50 flex justify-center items-center p-4">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-title font-bold text-lg" id="modal-title"></div>
            <div class="modal-actions">
                <a id="modal-download" href="#" target="_blank" class="bg-white text-slate-900 hover:bg-gray-200 px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition-colors"><i data-lucide="edit-3" class="w-4 h-4"></i> USAR PLANTILLA</a>
                <button class="modal-close-btn p-2 text-white hover:text-gray-300"><i data-lucide="x" class="w-6 h-6"></i></button>
            </div>
        </div>
        <div class="modal-image-container">
            <img id="modal-mockup" src="" alt="Vista previa de la plantilla">
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();

    const modal = document.getElementById('modal');
    const modalMockup = document.getElementById('modal-mockup');
    const modalTitle = document.getElementById('modal-title');
    const modalDownload = document.getElementById('modal-download');
    const closeModalBtn = modal.querySelector('.modal-close-btn');
    const templateGrid = document.getElementById('template-grid');
    const searchInput = document.getElementById('search-input');
    const filterButtons = document.getElementById('category-filter-buttons');
    const noResultsMessage = document.getElementById('no-results-message');
    const loadMoreContainer = document.getElementById('load-more-container');

    const allTemplatesData = <?php echo json_encode($todasLasPlantillas, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    let filtersAreActive = false;

    // --- NOTIFICACIÓN DE DESCARGA ---
    // Listener para el botón de descarga en el modal
    if (modalDownload) {
        modalDownload.addEventListener('click', () => {
            showToast("DESCARGA INICIADA", "success");
        });
    }
    
    // Listener para botones de descarga en la cuadrícula (Delegación de eventos)
    if (templateGrid) {
        templateGrid.addEventListener('click', (e) => {
            const downloadBtn = e.target.closest('.template-card__btn--download');
            if (downloadBtn) {
                showToast("DESCARGA INICIADA", "success");
            }
        });
    }

    const createCardHTML = (template) => {
        const templateUrl = template.filename;
        const title = template.title;
        const mockupPath = `ia-stock/${template.mockup_image}`;
        return `
        <article class="template-card" data-template-url="${templateUrl}" data-category="${template.category}" data-title="${title}" data-mockup="${mockupPath}" data-id="${template.id}">
            <div class="template-card__thumbnail">
                <div class="thumb-skeleton"></div>
                <img src="${mockupPath}" alt="Maqueta de ${title}" loading="lazy" onerror="this.onerror=null;this.src='https://placehold.co/640x480/eef2f7/9aa4b2?text=Plantilla';">
            </div>
            <div class="template-card__content">
                <span class="info-pill pill--id"><i data-lucide="asterisk"></i>${template.id}</span>
                <span class="info-pill pill--category"><i data-lucide="folder"></i>${template.category}</span>
            </div>
            <div class="template-card__actions">
                <button type="button" class="template-card__btn template-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                <a href="${templateUrl}" target="_blank" class="template-card__btn template-card__btn--download"><i data-lucide="edit-3" class="w-4 h-4"></i> USAR</a>
            </div>
        </article>`;
    };

    const io = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (!entry.isIntersecting) return;
            const card = entry.target;
            const img = card.querySelector('img');
            const done = () => { card.classList.add('loaded'); const sk = card.querySelector('.thumb-skeleton'); if (sk) sk.remove(); };
            if (img.complete) { done(); } else { img.addEventListener('load', done, { once: true }); }
            io.unobserve(card);
        });
    }, { rootMargin: '200px 0px' });

    document.querySelectorAll('.template-card').forEach(card => io.observe(card));

    const applyFiltersAndRender = () => {
        const searchTerm = searchInput.value.toLowerCase();
        const category = filterButtons.querySelector('.active').dataset.filter;
        if (!filtersAreActive && searchTerm === '' && category === 'all') return;
        filtersAreActive = true;
        loadMoreContainer.style.display = 'none';

        const filteredTemplates = allTemplatesData.filter(template => {
            const matchesId = template.id.toLowerCase().includes(searchTerm);
            const matchesCategory = (category === 'all' || template.category === category);
            return matchesId && matchesCategory;
        });

        templateGrid.innerHTML = filteredTemplates.map(createCardHTML).join('');
        noResultsMessage.style.display = filteredTemplates.length === 0 ? 'block' : 'none';
        templateGrid.querySelectorAll('.template-card').forEach(card => io.observe(card));
        lucide.createIcons();
    };

    searchInput.addEventListener('input', applyFiltersAndRender);
    filterButtons.addEventListener('click', (e) => {
        const button = e.target.closest('button');
        if (!button) return;
        filterButtons.querySelector('.active').classList.remove('active');
        button.classList.add('active');
        applyFiltersAndRender();
    });

    const openModal = (mockupUrl, templateUrl, title) => {
        modalMockup.src = mockupUrl;
        modalTitle.textContent = title;
        modalDownload.href = templateUrl;
        modal.classList.add('show');
    };
    const closeModal = () => {
        modal.classList.remove('show');
        modalMockup.src = "";
    };
    closeModalBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
    templateGrid.addEventListener('click', (e) => {
        const isViewBtn = e.target.closest('.template-card__btn--view');
        if (!isViewBtn) return;
        const card = isViewBtn.closest('.template-card');
        openModal(card.dataset.mockup, card.dataset.templateUrl, card.dataset.title);
    });

    let currentPage = 1;
    const itemsPerPage = 8;
    const loadMoreBtn = document.getElementById('load-more-btn');
    if (allTemplatesData.length <= initialTemplatesToShow) {
        loadMoreContainer.style.display = 'none';
    }
    loadMoreBtn.addEventListener('click', () => {
        if (filtersAreActive) return;
        const start = currentPage * itemsPerPage;
        const end = start + itemsPerPage;
        const newTemplates = allTemplatesData.slice(start, end);
        if (newTemplates.length > 0) {
            templateGrid.insertAdjacentHTML('beforeend', newTemplates.map(createCardHTML).join(''));
            currentPage++;
            templateGrid.querySelectorAll('.template-card:not(.loaded)').forEach(card => io.observe(card));
            lucide.createIcons();
        }
        if (end >= allTemplatesData.length) {
            loadMoreContainer.style.display = 'none';
        }
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>