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

// --- Tu código de conexión a la base de datos ---
$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');
    } 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($todosLosAudios);

$initialAudiosToShow = 8;
$audiosIniciales = array_slice($todosLosAudios, 0, $initialAudiosToShow);
$totalAudios     = count($todosLosAudios);

$musicFilters = [
    'all' => 'TODOS',
    'true' => 'CON MÚSICA',
    'false' => 'SIN MÚSICA',
];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Stock Audios <?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>
        /* --- Estilos de la página --- */
        .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; }
        .audio-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); }
        .audio-card:hover { transform: translateY(-6px); box-shadow: 0 18px 28px -14px rgba(2,6,23,.35); }
        .audio-icon-container { display: flex; justify-content: center; align-items: center; padding: 2rem; background: var(--color-primary); border-bottom: 1px solid #e5e7eb; }
        .audio-icon-container svg { color: #ffffff; width: 4rem; height: 4rem; }
        .audio-card__content { padding: .8rem 1rem; display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; }
        .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: #e0e7ff; color: #3730a3; }
        .pill--music-status { background: #d1fae5; color: #065f46; }
        .pill--no-music-status { background: #fee2e2; color: #991b1b; }
        .audio-card__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .7rem; padding: 0 1rem 1rem; margin-top: .5rem; }
        .audio-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; }
        .audio-card__btn--view { background: #f3f4f6; color: #111827; border: 1px solid #e5e7eb; }
        .audio-card__btn--view:hover { background: #e7eaf0; }
        .audio-card__btn--download { background: var(--color-primary); color: #fff; }
        .audio-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%, 500px); 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; padding: 2rem; }
        .modal-body audio { width: 100%; }
        #audio-grid-container { margin-top: 2rem; }
        
        /* --- ESTILOS PARA FILTROS (ACTUALIZADOS PARA COINCIDIR CON 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; }
        
        /* CAMBIO: Se aplica el estilo del contenedor gris de la galería de imágenes */
        .music-filters { 
            display: flex; 
            gap: .5rem; 
            background: #e5e7eb; 
            padding: .3rem; 
            border-radius: 8px;
        }
        .music-filters button { 
            padding: .5rem 1rem; 
            border: none; /* Se quita el borde */
            background: transparent; /* Fondo transparente */
            border-radius: 6px; /* Bordes menos redondeados */
            font-weight: 700; 
            cursor: pointer; 
            transition: all .2s; 
            color: #374151;
        }
        .music-filters button.active { 
            background: #ffffff; /* El botón activo es blanco */
            color: var(--color-primary); 
            box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* Sombra suave */
        }
        #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="Audios Para Negocios de Limpieza"
    data-page-subtitle="Recursos de audio para potenciar tu marca"
    data-page-icon="volume-2">

   <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)]">Audios</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 audios 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="#audio-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="headphones" class="w-5 h-5"></i> EXPLORAR AUDIOS</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 $totalAudios; ?></p></div>
                                        <p class="text-sm uppercase font-semibold tracking-wider" style="color: var(--color-highlight);">Audios 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: AUD001)">
                    </div>
                    <div class="music-filters" id="music-filter-buttons">
                        <?php foreach ($musicFilters as $key => $label): ?>
                            <button type="button" data-filter="<?php echo htmlspecialchars($key); ?>" class="<?php echo ($key === 'all' ? 'active' : ''); ?>">
                                <?php echo htmlspecialchars($label); ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>

            <section id="audio-grid-container">
                <div id="audio-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-6">
                    <?php foreach ($audiosIniciales as $audio): ?>
                        <?php
                            $audioPath = 'ia-stock/' . htmlspecialchars($audio['filename']);
                            $category = htmlspecialchars($audio['category']);
                            $title = pathinfo($audio['filename'], PATHINFO_FILENAME);
                            $id = htmlspecialchars($audio['id']);
                            $hasMusic = $audio['has_music'];
                        ?>
                        <article class="audio-card" 
                                 data-full-audio="<?php echo $audioPath; ?>" 
                                 data-category="<?php echo $category; ?>" 
                                 data-title="<?php echo htmlspecialchars($title); ?>" 
                                 data-id="<?php echo $id; ?>" 
                                 data-has-music="<?php echo $hasMusic ? 'true' : 'false'; ?>">
                            <div class="audio-icon-container"><i data-lucide="volume-2"></i></div>
                            <div class="audio-card__content">
                                <span class="info-pill pill--id"><i data-lucide="asterisk"></i><?php echo $id; ?></span>
                                <span class="info-pill <?php echo $hasMusic ? 'pill--music-status' : 'pill--no-music-status'; ?>">
                                    <i data-lucide="<?php echo $hasMusic ? 'music' : 'mic-vocal'; ?>"></i>
                                    <?php echo $hasMusic ? 'CON MÚSICA' : 'SOLO AUDIO'; ?>
                                </span>
                            </div>
                            <div class="audio-card__actions">
                                <button type="button" class="audio-card__btn audio-card__btn--view"><i data-lucide="ear" class="w-4 h-4"></i> ESCUCHAR</button>
                                <a href="<?php echo $audioPath; ?>" download class="audio-card__btn audio-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 AUDIOS</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"><audio id="modal-audio" controls autoplay></audio></div>
    </div>
</div>

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

    const modal = document.getElementById('modal');
    const modalAudio = document.getElementById('modal-audio');
    const modalTitle = document.getElementById('modal-title');
    const modalDownload = document.getElementById('modal-download');
    const closeModalBtn = modal.querySelector('.modal-close-btn');
    const audioGrid = document.getElementById('audio-grid');
    const searchInput = document.getElementById('search-input');
    const musicFilterButtons = document.getElementById('music-filter-buttons');
    const noResultsMessage = document.getElementById('no-results-message');
    const loadMoreContainer = document.getElementById('load-more-container');

    const allAudiosData = <?php echo json_encode($todosLosAudios, 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 (audioGrid) {
        audioGrid.addEventListener('click', (e) => {
            const downloadBtn = e.target.closest('.audio-card__btn--download');
            if (downloadBtn) {
                showToast("DESCARGA INICIADA", "success");
            }
        });
    }

    const createCardHTML = (audio) => {
        const audioPath = `ia-stock/${audio.filename}`;
        const title = (audio.filename || '').split('/').pop().replace(/\.[^.]+$/, '');
        const hasMusic = audio.has_music;
        const musicPillClass = hasMusic ? 'pill--music-status' : 'pill--no-music-status';
        const musicPillIcon = hasMusic ? 'music' : 'mic-vocal';
        const musicPillText = hasMusic ? 'CON MÚSICA' : 'SOLO AUDIO';

        return `
        <article class="audio-card" data-full-audio="${audioPath}" data-category="${audio.category}" data-title="${title}" data-id="${audio.id}" data-has-music="${hasMusic ? 'true' : 'false'}">
            <div class="audio-icon-container"><i data-lucide="volume-2"></i></div>
            <div class="audio-card__content">
                <span class="info-pill pill--id"><i data-lucide="asterisk"></i>${audio.id}</span>
                <span class="info-pill ${musicPillClass}"><i data-lucide="${musicPillIcon}"></i>${musicPillText}</span>
            </div>
            <div class="audio-card__actions">
                <button type="button" class="audio-card__btn audio-card__btn--view"><i data-lucide="ear" class="w-4 h-4"></i> ESCUCHAR</button>
                <a href="${audioPath}" download class="audio-card__btn audio-card__btn--download"><i data-lucide="download" class="w-4 h-4"></i> DESCARGAR</a>
            </div>
        </article>`;
    };

    const applyFiltersAndRender = () => {
        const searchTerm = searchInput.value.toLowerCase();
        const musicFilter = musicFilterButtons.querySelector('.active').dataset.filter;

        if (!filtersAreActive && searchTerm === '' && musicFilter === 'all') return;
        filtersAreActive = true;
        
        loadMoreContainer.style.display = 'none';

        const filteredAudios = allAudiosData.filter(audio => {
            const matchesId = audio.id.toLowerCase().includes(searchTerm);
            const matchesMusic = (musicFilter === 'all' || (audio.has_music ? 'true' : 'false') === musicFilter);
            return matchesId && matchesMusic;
        });

        audioGrid.innerHTML = filteredAudios.map(createCardHTML).join('');
        
        noResultsMessage.style.display = filteredAudios.length === 0 ? 'block' : 'none';
        
        lucide.createIcons();
    };

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

    const openModal = (audioUrl, title = 'Reproduciendo…') => {
        modalAudio.src = audioUrl;
        modalDownload.href = audioUrl;
        modalDownload.download = title;
        modalTitle.textContent = title;
        modal.classList.add('show');
    };
    const closeModal = () => {
        modal.classList.remove('show');
        modalAudio.pause();
        modalAudio.src = "";
    };
    closeModalBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
    audioGrid.addEventListener('click', (e) => {
        const isViewBtn = e.target.closest('.audio-card__btn--view');
        if (!isViewBtn) return;
        const card = isViewBtn.closest('.audio-card');
        openModal(card.dataset.fullAudio, card.dataset.title);
    });

    // --- Lógica original de "Cargar Más" ---
    let currentPage = 1;
    const itemsPerPage = 8;
    const loadMoreBtn = document.getElementById('load-more-btn');
    if (allAudiosData.length <= <?php echo $initialAudiosToShow; ?>) {
        loadMoreContainer.style.display = 'none';
    }
    loadMoreBtn.addEventListener('click', () => {
        if (filtersAreActive) return;
        const start = currentPage * itemsPerPage;
        const end = start + itemsPerPage;
        const newAudios = allAudiosData.slice(start, end);
        if (newAudios.length > 0) {
            audioGrid.insertAdjacentHTML('beforeend', newAudios.map(createCardHTML).join(''));
            currentPage++;
            lucide.createIcons();
        }
        if (end >= allAudiosData.length) {
            loadMoreContainer.style.display = 'none';
        }
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>