<?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 () {
    const isMobile = window.innerWidth <= 768;
    let page = 1;
    let loading = false;
    let noMoreItems = false;
    let currentFilter = "artist-video";
    let currentSearch = "";
    let currentView = "grid";
    const perPage = isMobile ? 12 : 24; // ⚡ menos items en móvil

    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 || currentSearch.length > 0) return;
        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: isMobile ? "400px" : "800px" // ⚡ menor en móvil
        });
        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;
                }

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

                // ⚡ carga inmediata sin esperar imágenes en móvil
                const process = () => {
                    grid.append(...items);
                    lazyLoadImages(items);
                    iso.appended(items);
                    iso.layout();
                    page++;
                    loading = false;
                    if (reset) attachObserver();
                };

                if (isMobile) {
                    process();
                } else {
                    imagesLoaded(items, process);
                }
            })
            .catch(err => {
                if (err.name !== 'AbortError') console.error(err);
                loading = false;
            });
    }

    function lazyLoadImages(items) {
    const images = Array.from(items).flatMap(item =>
        Array.from(item.querySelectorAll('img.lazy-fade[data-src]'))
    );

    if ('IntersectionObserver' in window) {
        const lazyObserver = new IntersectionObserver((entries, obs) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.getAttribute('data-src');
                    img.onload = () => img.classList.add('lazy-loaded');
                    obs.unobserve(img);
                }
            });
        }, {
            rootMargin: "200px",
            threshold: 0.1
        });

        images.forEach(img => lazyObserver.observe(img));
    } else {
        // Fallback para navegadores antiguos
        images.forEach(img => {
            img.src = img.getAttribute('data-src');
            img.classList.add('lazy-loaded');
        });
    }
}

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

                // ⚠️ Carga diferida solo si no es móvil
                if (!isMobile) {
                    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);
                            });
                    }, 100);
                }
            })
            .catch(err => {
                if (err.name !== 'AbortError') console.error(err);
            });
    }

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

    // 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 optimizado
    searchInput.addEventListener("input", function () {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            const newSearch = searchInput.value.trim();
            if (newSearch === currentSearch) return; // ⚡ no recargar si no cambia

            currentSearch = newSearch;

            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();
            }
        }, 250); // ⚡ debounce más corto
    });

    // Vista grid/lista
    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 + reveal + precarga
    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;

            if (!noMoreItems && scrollPosition >= pageHeight - (isMobile ? 800 : 1500)) {
                loadItems();
            }

            if (noMoreItems && scrollPosition >= pageHeight - 50 && scrollPosition >= gridBottom) {
                activarFooterReveal();
            }
        }
    });

    // 🚀 Primera carga
    loadItems(true);
});
</script>





<?php get_footer(); ?>
