<?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';

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();

// Datos de videos
require_once 'ia-stock/videos-limpieza.php';

shuffle($todosLosVideos);

$initialVideosToShow = 8;
$videosIniciales = array_slice($todosLosVideos, 0, $initialVideosToShow);
$totalVideos     = count($todosLosVideos);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Stock Videos 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 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">

    <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; }
        .video-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); }
        .video-card:hover{ transform: translateY(-6px); box-shadow:0 18px 28px -14px rgba(2,6,23,.35); }
        .video-card__thumbnail{ position:relative; background:#eef2f7; aspect-ratio: 16/9; overflow:hidden; }
        .video-card__thumbnail img{ width:100%; height:100%; object-fit:cover; display:block; opacity:0; transition:opacity .25s ease, transform .35s ease; }
        .video-card.loaded .video-card__thumbnail img{ opacity:1; }
        .video-card:hover .video-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} }
        .video-overlay{ position:absolute; inset:0; display:flex; align-items:center; justify-content:center; background:linear-gradient(180deg, rgba(0,0,0,.0), rgba(0,0,0,.35)); opacity:0; transition:opacity .25s ease; }
        .video-card:hover .video-overlay{ opacity:1; }
        .video-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--id{ background:#f3f4f6; color:#374151; }
        .pill--orientation{ background:#e0e7ff; color:#3730a3; }
        .video-card__actions{ display:grid; grid-template-columns:1fr 1fr; gap:.7rem; padding:0 1rem 1rem; margin-top:.5rem; }
        .video-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; }
        .video-card__btn--view{ background:#f3f4f6; color:#111827; border:1px solid #e5e7eb; }
        .video-card__btn--view:hover{ background:#e7eaf0; }
        .video-card__btn--download{ background:var(--color-primary); color:#fff; }
        .video-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-body { background: black; display: flex; align-items: center; justify-content: center; }
        .modal-body video { width: 100%; height: auto; max-height: 80vh; object-fit: contain; background: #000; }
        #video-grid-container { margin-top: 2rem; }

        .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; }
        .orientation-filters { display: flex; gap: .5rem; background: #e5e7eb; padding: .3rem; border-radius: 8px; }
        .orientation-filters button { padding: .5rem 1rem; border: none; background: transparent; border-radius: 6px; font-weight: 700; cursor: pointer; transition: all .2s; color: #374151; }
        .orientation-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="Videos Para Negocios de Limpieza"
    data-page-subtitle="Recursos de video para potenciar tu marca"
    data-page-icon="video">
    
   <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)]">Videos</span> Para Negocios<span class="block text-white/90 text-2xl md:text-4xl mt-1">De Limpieza Profesional</span></h1>
                                <p class="text-white/80 mt-4 max-w-2xl text-base md:text-lg">Ahorra tiempo y encuentra videos profesionales listos para usar en tus anuncios y redes sociales. Haz que tu negocio de limpieza destaque.</p>
                                <div class="mt-6 flex flex-wrap gap-3"><a href="#video-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="play-circle" class="w-5 h-5"></i> EXPLORAR VIDEOS</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 $totalVideos; ?></p></div>
                                        <p class="text-sm uppercase font-semibold tracking-wider" style="color: var(--color-highlight);">Videos 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: VID001)">
                    </div>
                    <div class="orientation-filters" id="orientation-filter-buttons">
                        <button type="button" data-filter="all" class="active">TODOS</button>
                        <button type="button" data-filter="horizontal">HORIZONTALES</button>
                        <button type="button" data-filter="vertical">VERTICALES</button>
                    </div>
                </div>
            </section>

            <section id="video-grid-container">
                <div id="video-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <?php foreach ($videosIniciales as $video): ?>
                        <?php
                            $id            = htmlspecialchars($video['id']);
                            $videoPath     = 'ia-stock/' . htmlspecialchars($video['filename']);
                            $thumbnailPath = 'ia-stock/' . htmlspecialchars($video['thumbnail']);
                            $orientation   = htmlspecialchars($video['orientation']);
                            $title         = pathinfo($video['filename'], PATHINFO_FILENAME);
                        ?>
                        <article class="video-card"
                                 data-full-video="<?php echo $videoPath; ?>"
                                 data-thumbnail="<?php echo $thumbnailPath; ?>"
                                 data-orientation="<?php echo $orientation; ?>"
                                 data-title="<?php echo htmlspecialchars($title); ?>"
                                 data-id="<?php echo $id; ?>">
                            <div class="video-card__thumbnail">
                                <div class="thumb-skeleton" aria-hidden="true"></div>
                                <img src="<?php echo $thumbnailPath; ?>" alt="Miniatura: <?php echo htmlspecialchars($video['category']); ?>" loading="lazy" onerror="this.onerror=null;this.src='https://placehold.co/640x360/eef2f7/9aa4b2?text=Sin+miniatura';">
                                <div class="video-overlay video-card__btn--view"><i data-lucide="play-circle" class="w-12 h-12 text-white/90"></i></div>
                            </div>
                            <div class="video-card__content">
                                <span class="info-pill pill--id"><i data-lucide="asterisk"></i><?php echo $id; ?></span>
                                <?php if ($orientation === 'vertical'): ?>
                                    <span class="info-pill pill--orientation"><i data-lucide="rectangle-vertical"></i> Vertical</span>
                                <?php else: ?>
                                    <span class="info-pill pill--orientation"><i data-lucide="rectangle-horizontal"></i> Horizontal</span>
                                <?php endif; ?>
                            </div>
                            <div class="video-card__actions">
                                <button type="button" class="video-card__btn video-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                                <a href="<?php echo $videoPath; ?>" download class="video-card__btn video-card__btn--download"><i data-lucide="download" class="w-4 h-4"></i> DESCARGAR</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 VIDEOS</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" id="modal-title">Reproduciendo…</div>
            <div class="modal-actions">
                <a id="modal-download" href="#" download 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="download" class="w-4 h-4"></i> DESCARGAR</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-body"><video id="modal-video" controls autoplay loop playsinline></video></div>
    </div>
</div>

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

    const modal = document.getElementById('modal');
    const modalVideo = document.getElementById('modal-video');
    const modalTitle = document.getElementById('modal-title');
    const modalDownload = document.getElementById('modal-download');
    const closeModalBtn = modal.querySelector('.modal-close-btn');
    const videoGrid = document.getElementById('video-grid');
    const searchInput = document.getElementById('search-input');
    const filterButtons = document.getElementById('orientation-filter-buttons');
    const noResultsMessage = document.getElementById('no-results-message');
    const loadMoreContainer = document.getElementById('load-more-container');

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

    const createCardHTML = (video) => {
        const videoPath = `ia-stock/${video.filename}`;
        const thumbnailPath = `ia-stock/${video.thumbnail}`;
        const orientationPill = video.orientation === 'vertical'
            ? `<span class="info-pill pill--orientation"><i data-lucide="rectangle-vertical"></i> Vertical</span>`
            : `<span class="info-pill pill--orientation"><i data-lucide="rectangle-horizontal"></i> Horizontal</span>`;
        const title = (video.filename || '').split('/').pop().replace(/\.[^.]+$/, '');

        return `
        <article class="video-card" data-full-video="${videoPath}" data-thumbnail="${thumbnailPath}" data-orientation="${video.orientation}" data-title="${title}" data-id="${video.id}">
            <div class="video-card__thumbnail">
                <div class="thumb-skeleton"></div>
                <img src="${thumbnailPath}" alt="Miniatura: ${video.category}" loading="lazy" onerror="this.onerror=null;this.src='https://placehold.co/640x360/eef2f7/9aa4b2?text=Sin+miniatura';">
                <div class="video-overlay video-card__btn--view"><i data-lucide="play-circle" class="w-12 h-12 text-white/90"></i></div>
            </div>
            <div class="video-card__content">
                <span class="info-pill pill--id"><i data-lucide="asterisk"></i>${video.id}</span>
                ${orientationPill}
            </div>
            <div class="video-card__actions">
                <button type="button" class="video-card__btn video-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                <a href="${videoPath}" download class="video-card__btn video-card__btn--download"><i data-lucide="download" class="w-4 h-4"></i> DESCARGAR</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('.video-card').forEach(card => io.observe(card));

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

        const filteredVideos = allVideosData.filter(video => {
            const matchesId = video.id.toLowerCase().includes(searchTerm);
            const matchesOrientation = (orientation === 'all' || video.orientation === orientation);
            return matchesId && matchesOrientation;
        });

        videoGrid.innerHTML = filteredVideos.map(createCardHTML).join('');
        noResultsMessage.style.display = filteredVideos.length === 0 ? 'block' : 'none';
        videoGrid.querySelectorAll('.video-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 = (videoUrl, title='Reproduciendo…') => {
        modalVideo.src = videoUrl;
        modalDownload.href = videoUrl;
        modalTitle.textContent = title;
        modal.classList.add('show');
    };
    const closeModal = () => {
        modal.classList.remove('show');
        modalVideo.pause();
        modalVideo.src = "";
    };
    closeModalBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
    videoGrid.addEventListener('click', (e) => {
        const isViewBtn = e.target.closest('.video-card__btn--view');
        if (!isViewBtn) return;
        const card = isViewBtn.closest('.video-card');
        openModal(card.dataset.fullVideo, card.dataset.title);
    });

    let currentPage = 1;
    const itemsPerPage = 8;
    const loadMoreBtn = document.getElementById('load-more-btn');
    if (allVideosData.length <= initialVideosToShow) {
        loadMoreContainer.style.display = 'none';
    }
    loadMoreBtn.addEventListener('click', () => {
        if (filtersAreActive) return;
        const start = currentPage * itemsPerPage;
        const end = start + itemsPerPage;
        const newVideos = allVideosData.slice(start, end);
        if (newVideos.length > 0) {
            videoGrid.insertAdjacentHTML('beforeend', newVideos.map(createCardHTML).join(''));
            currentPage++;
            videoGrid.querySelectorAll('.video-card:not(.loaded)').forEach(card => io.observe(card));
            lucide.createIcons();
        }
        if (end >= allVideosData.length) {
            loadMoreContainer.style.display = 'none';
        }
    });
});
</script>
</body>
</html>