<?php
/*
 * Template Name: Archive NEW
 *
 * @package far_loop
 */
get_header();
?>

<div class="header-new-archive">
    <!-- Filtros -->
    <div class="archive-categories">
        <span data-filter="artist-video" class="is-active">Artist Videos</span>
		<span data-filter="artist">Artists</span>
        <span data-filter="professional">Professionals</span>
        <span data-filter="exhibition">Exhibitions</span>
        <span data-filter="exhibition-route">Exhibition Routes</span>
        <span data-filter="live">Live</span>
        <span data-filter="film-programme">Film Programmes</span>
        <span data-filter="venue-gallery">Venues & Galleries</span>
        <span data-filter="workshop">Workshops</span>
        <span data-filter="talk">Talks</span>
        <span data-filter="professional-meeting">Professional Meetings</span>
		<span data-filter="all" class="hide-filter-all">All</span>
    </div>

    <div class="archive-search">
		<svg class="search-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
			<path fill="none" stroke="currentColor" stroke-width="2" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm11 3-6-6"/>
		</svg>
		<input type="text" id="archive-search-input" placeholder="What are you looking for?" />
	</div>

    
    
</div>		

<div id="toggle-view-archive" class="is-grid">List View</div>

<!-- Contenedor grid -->
<div class="u_pt-3 u_pt-md-6 archive-grid-container">
    <div class="l_container u_mv-5">
        <div class="archive-grid"></div>
        <div id="load-more-trigger" style="height: 50px;"></div>
    </div>
</div>

<!-- Contenedor texto -->
<div class="archive-text-container l_container u_mv-5" style="display:none;"></div>

<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    let page = 1;
    let loading = false;
    let noMoreItems = false;
    let currentFilter = "artist-video";
    let currentSearch = "";
    let currentView = "grid";
    const perPage = 24;

    const grid = document.querySelector('.archive-grid');
    const textContainer = document.querySelector('.archive-text-container');
    const gridContainer = document.querySelector('.archive-grid-container');
    const toggleBtn = document.getElementById("toggle-view-archive");
    const searchInput = document.getElementById("archive-search-input");

    const iso = new Isotope(grid, { itemSelector: '.archive-item', layoutMode: 'fitRows' });

    const footer = document.querySelector(".reveal-footer");
    let footerActive = false;
    let observer = null;

    let currentController = null;
    let searchTimeout = null;

    function activarFooterReveal() {
        if (footerActive) return; // ya activo
        if (currentSearch && currentSearch.length > 0) return; // 🚫 Si hay búsqueda, no mostrar footer
        footerActive = true;
        document.body.classList.add("footer-reveal-active");
        if (footer) footer.style.transform = "translateY(0%)";
    }

    function resetGrid() {
        if (observer) observer.disconnect();
        iso.remove(iso.getItemElements());
        grid.innerHTML = "";
        iso.layout();
        page = 1;
        loading = false;
        noMoreItems = false;
        footerActive = false;
        document.body.classList.remove("footer-reveal-active");
        if (footer) footer.style.transform = "translateY(100%)";
    }

    function attachObserver() {
        const trigger = document.querySelector("#load-more-trigger");
        if (!trigger) return;
        observer = new IntersectionObserver(entries => {
            if (entries[0].isIntersecting && !loading && !noMoreItems && !footerActive) {
                loadItems();
            }
        }, { rootMargin: "800px" });
        observer.observe(trigger);
    }

    function cancelPreviousRequest() {
        if (currentController) {
            currentController.abort();
        }
        currentController = new AbortController();
        return currentController.signal;
    }

    function loadItems(reset = false) {
        if (loading || (noMoreItems && !reset)) return;
        loading = true;

        if (reset) {
            resetGrid();
        }

        const signal = cancelPreviousRequest();

        fetch(`<?php echo admin_url('admin-ajax.php'); ?>?action=load_archive_items&page=${page}&ppp=${perPage}&filter=${currentFilter}&search=${encodeURIComponent(currentSearch)}`, { signal })
            .then(res => res.text())
            .then(html => {
                if (!html.trim()) {
                    noMoreItems = true;
                    loading = false;
                    return; // ya no mostramos footer aquí
                }

                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = html;
                const items = Array.from(tempDiv.children);

                imagesLoaded(items, function () {
                    grid.append(...items);
                    iso.appended(items);
                    iso.layout();
                    page++;
                    loading = false;
                    if (reset) attachObserver();
                });
            })
            .catch(err => {
                if (err.name !== 'AbortError') console.error(err);
                loading = false;
            });
    }

    function loadTextView() {
        textContainer.innerHTML = "<p>Loading...</p>";
        const signal = cancelPreviousRequest();

        fetch(`<?php echo admin_url('admin-ajax.php'); ?>?action=load_archive_text&filter=${currentFilter}&search=${encodeURIComponent(currentSearch)}&offset=0&limit=4`, { signal })
            .then(res => res.text())
            .then(html => {
                textContainer.innerHTML = `<div class="archive-text-view">${html}</div>`;
                animateColumns(textContainer.querySelectorAll('.edition-group'));
                setTimeout(() => {
                    fetch(`<?php echo admin_url('admin-ajax.php'); ?>?action=load_archive_text&filter=${currentFilter}&search=${encodeURIComponent(currentSearch)}&offset=4&limit=0`)
                        .then(res => res.text())
                        .then(extraHtml => {
                            const container = textContainer.querySelector('.archive-text-view');
                            const temp = document.createElement('div');
                            temp.innerHTML = extraHtml;
                            const newCols = temp.querySelectorAll('.edition-group');
                            newCols.forEach(col => container.appendChild(col));
                            animateColumns(newCols);
                        });
                }, 150);
            })
            .catch(err => {
                if (err.name !== 'AbortError') console.error(err);
            });
    }

    function animateColumns(columns) {
        columns.forEach((col, i) => {
            col.style.animationDelay = `${i * 0.15}s`;
        });
    }

    // Cambio de filtro
    document.querySelectorAll(".archive-categories span").forEach(cat => {
        cat.addEventListener("click", function(){
            if (this.classList.contains("is-active")) return;
            document.querySelectorAll(".archive-categories span").forEach(c => c.classList.remove("is-active"));
            this.classList.add("is-active");
            currentFilter = this.getAttribute("data-filter");
            currentSearch = "";
            searchInput.value = "";

            if (currentView === "grid") {
                loadItems(true);
            } else {
                loadTextView();
            }
        });
    });

    // Búsqueda con debounce
    searchInput.addEventListener("input", function(){
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentSearch = searchInput.value.trim();

            document.querySelectorAll(".archive-categories span").forEach(c => c.classList.remove("is-active"));
            document.querySelector('.archive-categories span[data-filter="all"]').classList.add("is-active");
            currentFilter = "all";

            if (currentView === "grid") {
                loadItems(true);
            } else {
                loadTextView();
            }
        }, 300);
    });

    // Botón toggle vista
    toggleBtn.addEventListener("click", function(){
        if (currentView === "grid") {
            currentView = "text";
            toggleBtn.textContent = "Grid View";
            gridContainer.style.display = "none";
            textContainer.style.display = "block";
            loadTextView();
        } else {
            currentView = "grid";
            toggleBtn.textContent = "List View";
            textContainer.style.display = "none";
            gridContainer.style.display = "block";
            loadItems(true);
        }
    });

    // Scroll para precarga y footer reveal (doble check)
    window.addEventListener('scroll', () => {
        if (currentView === "grid" && !loading && !footerActive) {
            const scrollPosition = window.scrollY + window.innerHeight;
            const pageHeight = document.body.offsetHeight;
            const gridBottom = grid.offsetTop + grid.offsetHeight;

            // precarga
            if (!noMoreItems && scrollPosition >= pageHeight - 1500) {
                loadItems();
            }

            // footer reveal solo si se cumplen las 3 condiciones
            if (noMoreItems && scrollPosition >= pageHeight - 50 && scrollPosition >= gridBottom) {
                activarFooterReveal();
            }
        }
    });

    // Carga inicial grid
    loadItems(true);
});
</script>





<?php get_footer(); ?>
