/**
 * Palace Properties - AJAX Filtering, Sorting & Pagination
 * No jQuery dependency - vanilla JS
 */
(function () {
    'use strict';

    var grid = document.getElementById('ipp-properties-grid');
    var form = document.getElementById('ipp-filter-form');
    var loadMoreBtn = document.getElementById('ipp-load-more');
    var countEl = document.querySelector('.ipp-archive-count');

    if (!grid || !form) return;

    var currentPage = 1;
    var maxPages = loadMoreBtn ? parseInt(loadMoreBtn.getAttribute('data-max') || '1', 10) : 1;
    var isLoading = false;
    var debounceTimer = null;

    // ─── URL State Management ────────────────────────────────────────

    function getFilterParams() {
        var data = new FormData(form);
        var params = {};
        data.forEach(function (value, key) {
            if (value && key !== 'filter') {
                params[key] = value;
            }
        });
        return params;
    }

    function updateURL(params) {
        var url = new URL(window.location.href);
        url.search = '';
        Object.keys(params).forEach(function (key) {
            if (params[key]) {
                url.searchParams.set(key, params[key]);
            }
        });
        if (Object.keys(params).length > 0) {
            url.searchParams.set('filter', '1');
        }
        window.history.pushState({}, '', url.toString());
    }

    // ─── AJAX Request ────────────────────────────────────────────────

    function fetchProperties(page, append) {
        if (isLoading) return;
        isLoading = true;

        var params = getFilterParams();
        params.page = page;
        params.per_page = 9;
        params.action = 'ipp_filter_properties';
        params.nonce = (typeof ipp_ajax !== 'undefined') ? ipp_ajax.nonce : '';

        // Build POST body
        var body = new URLSearchParams();
        Object.keys(params).forEach(function (key) {
            body.append(key, params[key]);
        });

        // Show loading state
        if (!append) {
            grid.classList.add('ipp-loading');
            grid.insertAdjacentHTML('beforeend', '<div class="ipp-skeleton-grid" id="ipp-skeleton">' +
                '<div class="ipp-skeleton ipp-skeleton--card"></div>'.repeat(6) + '</div>');
        }

        if (loadMoreBtn) {
            loadMoreBtn.disabled = true;
            loadMoreBtn.innerHTML = '<svg class="ipp-spinner" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" opacity="0.3"/><path d="M12 2a10 10 0 0 1 10 10"/></svg> Loading...';
        }

        var ajaxUrl = (typeof ipp_ajax !== 'undefined') ? ipp_ajax.ajax_url :
            ((typeof ajax_params !== 'undefined') ? ajax_params.ajax_url : '/wp-admin/admin-ajax.php');

        fetch(ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body.toString()
        })
            .then(function (res) { return res.json(); })
            .then(function (response) {
                isLoading = false;

                // Remove skeleton
                var skeleton = document.getElementById('ipp-skeleton');
                if (skeleton) skeleton.remove();
                grid.classList.remove('ipp-loading');

                if (response.success && response.data) {
                    if (append) {
                        grid.insertAdjacentHTML('beforeend', response.data.html);
                    } else {
                        grid.innerHTML = response.data.html;
                    }

                    maxPages = response.data.max_pages || 1;
                    currentPage = response.data.current_page || page;

                    // Update count
                    if (countEl) {
                        countEl.innerHTML = '<strong>' + response.data.total_count + '</strong> ' +
                            (response.data.total_count === 1 ? 'Property' : 'Properties');
                    }

                    // Update load more
                    if (loadMoreBtn) {
                        if (currentPage >= maxPages) {
                            loadMoreBtn.style.display = 'none';
                        } else {
                            loadMoreBtn.style.display = '';
                            loadMoreBtn.setAttribute('data-page', currentPage);
                            loadMoreBtn.setAttribute('data-max', maxPages);
                        }
                    }

                    // No results — only show message on fresh search, not on load-more
                    if (!append && (!response.data.html || response.data.html.trim() === '')) {
                        grid.innerHTML = '<div class="ipp-no-results"><h2>No properties found</h2><p>Try adjusting your search filters.</p></div>';
                    }

                    // Update URL
                    if (!append) {
                        updateURL(getFilterParams());
                    }
                }

                // Reset load more button
                if (loadMoreBtn) {
                    loadMoreBtn.disabled = false;
                    loadMoreBtn.innerHTML = 'Load More Properties <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>';
                }
            })
            .catch(function () {
                isLoading = false;
                grid.classList.remove('ipp-loading');
                var skeleton = document.getElementById('ipp-skeleton');
                if (skeleton) skeleton.remove();
                if (loadMoreBtn) {
                    loadMoreBtn.disabled = false;
                    loadMoreBtn.innerHTML = 'Load More Properties';
                }
            });
    }

    // ─── Event Listeners ─────────────────────────────────────────────

    // Form submit (search button)
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        currentPage = 1;
        fetchProperties(1, false);
    });

    // Dropdowns: filter on change
    var selects = form.querySelectorAll('.ipp-search__select');
    selects.forEach(function (select) {
        select.addEventListener('change', function () {
            currentPage = 1;
            fetchProperties(1, false);
        });
    });

    // Text input: debounced search
    var textInput = form.querySelector('.ipp-search__input[type="text"]');
    if (textInput) {
        textInput.addEventListener('input', function () {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(function () {
                currentPage = 1;
                fetchProperties(1, false);
            }, 400);
        });
    }

    // Load More button
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', function (e) {
            e.preventDefault();
            if (currentPage >= maxPages) return;
            currentPage++;
            fetchProperties(currentPage, true);
        });
    }

    // ─── Grid / List Toggle ──────────────────────────────────────────

    var gridBtn = document.querySelector('.ipp-view-grid');
    var listBtn = document.querySelector('.ipp-view-list');

    if (gridBtn && listBtn) {
        gridBtn.addEventListener('click', function () {
            grid.classList.remove('ipp-grid--list');
            gridBtn.classList.add('active');
            listBtn.classList.remove('active');
            localStorage.setItem('ipp_view', 'grid');
        });

        listBtn.addEventListener('click', function () {
            grid.classList.add('ipp-grid--list');
            listBtn.classList.add('active');
            gridBtn.classList.remove('active');
            localStorage.setItem('ipp_view', 'list');
        });

        // Restore preference
        if (localStorage.getItem('ipp_view') === 'list') {
            listBtn.click();
        }
    }

    // ─── Spinner CSS ─────────────────────────────────────────────────

    var style = document.createElement('style');
    style.textContent = [
        '.ipp-spinner { animation: ipp-spin 0.8s linear infinite; }',
        '@keyframes ipp-spin { to { transform: rotate(360deg); } }',
        '.ipp-loading { opacity: 0.5; pointer-events: none; transition: opacity 0.2s; }',
        '.ipp-skeleton-grid { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1.5rem; }',
        '.ipp-skeleton--card { height: 320px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: ipp-shimmer 1.5s ease-in-out infinite; border-radius: 12px; }',
        '@keyframes ipp-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }'
    ].join('\n');
    document.head.appendChild(style);

})();
