<?php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * Product Search & Filter Template
 */

$filterOptions = \Instinctor\Services\ProductSearchService::getFilterOptions();
?>

<div class="instinctor-search-filter">
    <!-- Search Bar -->
    <div class="instinctor-search-bar">
        <div class="instinctor-search-input-wrapper">
            <svg class="instinctor-search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input type="text" id="instinctor-search-input" placeholder="Search products..." autocomplete="off">
            <button type="button" id="instinctor-search-clear" style="display: none;">&times;</button>
        </div>
        <div id="instinctor-autocomplete" class="instinctor-autocomplete" style="display: none;"></div>
    </div>

    <div class="instinctor-filter-layout">
        <!-- Filters Sidebar -->
        <aside class="instinctor-filters-sidebar">
            <div class="instinctor-filter-header">
                <h3>Filters</h3>
                <button type="button" id="instinctor-clear-filters">Clear All</button>
            </div>

            <!-- Categories -->
            <?php if (!empty($filterOptions['categories'])): ?>
            <div class="instinctor-filter-group">
                <h4>Categories</h4>
                <ul class="instinctor-filter-list">
                    <?php foreach ($filterOptions['categories'] as $prodCat): ?>
                    <li>
                        <label>
                            <input type="checkbox" name="category" value="<?php echo esc_attr($prodCat->id); ?>">
                            <?php echo esc_html($prodCat->name); ?> <span class="count">(<?php echo esc_html($prodCat->count); ?>)</span>
                        </label>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <!-- Price Range -->
            <div class="instinctor-filter-group">
                <h4>Price</h4>
                <div class="instinctor-price-range">
                    <input type="number" id="instinctor-min-price" placeholder="Min" min="0" step="1">
                    <span>-</span>
                    <input type="number" id="instinctor-max-price" placeholder="Max" min="0" step="1">
                </div>
                <div class="instinctor-price-slider">
                    <input type="range" id="instinctor-price-slider" min="<?php echo intval($filterOptions['price_range']['min']); ?>" max="<?php echo intval($filterOptions['price_range']['max']); ?>" value="<?php echo intval($filterOptions['price_range']['max']); ?>">
                </div>
            </div>

            <!-- Rating -->
            <div class="instinctor-filter-group">
                <h4>Rating</h4>
                <ul class="instinctor-filter-list instinctor-rating-filter">
                    <?php for ($i = 4; $i >= 1; $i--): ?>
                    <li>
                        <label>
                            <input type="radio" name="min_rating" value="<?php echo intval($i); ?>">
                            <?php echo esc_html(str_repeat('★', $i) . str_repeat('☆', 5 - $i)); ?> & Up
                        </label>
                    </li>
                    <?php endfor; ?>
                </ul>
            </div>

            <!-- Stock -->
            <div class="instinctor-filter-group">
                <h4>Availability</h4>
                <label>
                    <input type="checkbox" id="instinctor-in-stock">
                    In Stock Only
                </label>
            </div>

            <!-- On Sale -->
            <div class="instinctor-filter-group">
                <label>
                    <input type="checkbox" id="instinctor-on-sale">
                    On Sale
                </label>
            </div>

            <!-- Dynamic Attributes -->
            <?php foreach ($filterOptions['attributes'] as $attrName => $values): ?>
            <div class="instinctor-filter-group">
                <h4><?php echo esc_html(ucfirst($attrName)); ?></h4>
                <ul class="instinctor-filter-list">
                    <?php foreach ($values as $value): ?>
                    <li>
                        <label>
                            <input type="checkbox" name="attr_<?php echo esc_attr($attrName); ?>" value="<?php echo esc_attr($value); ?>">
                            <?php echo esc_html($value); ?>
                        </label>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endforeach; ?>
        </aside>

        <!-- Products Grid -->
        <main class="instinctor-products-main">
            <div class="instinctor-products-header">
                <div class="instinctor-results-count">
                    <span id="instinctor-results-count">0</span> products
                </div>
                <div class="instinctor-sort-wrapper">
                    <label for="instinctor-sort">Sort by:</label>
                    <select id="instinctor-sort">
                        <?php foreach ($filterOptions['sort_options'] as $key => $label): ?>
                        <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div id="instinctor-products-grid" class="instinctor-products-grid">
                <!-- Products loaded via AJAX -->
            </div>

            <div id="instinctor-loading" class="instinctor-loading" style="display: none;">
                <div class="instinctor-spinner"></div>
                Loading...
            </div>

            <div id="instinctor-pagination" class="instinctor-pagination"></div>
        </main>
    </div>
</div>

<?php ob_start(); ?>
.instinctor-search-filter { max-width: 1200px; margin: 0 auto; padding: 20px; }
.instinctor-search-bar { position: relative; margin-bottom: 30px; }
.instinctor-search-input-wrapper { position: relative; }
.instinctor-search-icon { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #999; }
#instinctor-search-input { width: 100%; padding: 15px 45px 15px 45px; font-size: 16px; border: 2px solid #eee; border-radius: 8px; transition: border-color 0.2s; }
#instinctor-search-input:focus { outline: none; border-color: #1d1d1f; }
#instinctor-search-clear { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
.instinctor-autocomplete { position: absolute; top: 100%; left: 0; right: 0; background: #fff; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); z-index: 100; max-height: 400px; overflow-y: auto; }
.instinctor-autocomplete-item { display: flex; gap: 15px; padding: 12px 15px; cursor: pointer; border-bottom: 1px solid #f5f5f5; }
.instinctor-autocomplete-item:hover { background: #f9f9f9; }
.instinctor-autocomplete-item img { width: 50px; height: 50px; object-fit: cover; border-radius: 4px; }
.instinctor-autocomplete-item-info { flex: 1; }
.instinctor-autocomplete-item-name { font-weight: 500; }
.instinctor-autocomplete-item-price { color: #666; font-size: 14px; }

.instinctor-filter-layout { display: grid; grid-template-columns: 250px 1fr; gap: 30px; }
.instinctor-filters-sidebar { background: #fff; padding: 20px; border-radius: 8px; border: 1px solid #eee; height: fit-content; position: sticky; top: 20px; }
.instinctor-filter-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.instinctor-filter-header h3 { margin: 0; }
#instinctor-clear-filters { background: none; border: none; color: #666; cursor: pointer; font-size: 13px; }
#instinctor-clear-filters:hover { color: #e53935; }
.instinctor-filter-group { margin-bottom: 25px; padding-bottom: 20px; border-bottom: 1px solid #eee; }
.instinctor-filter-group:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.instinctor-filter-group h4 { margin: 0 0 12px; font-size: 14px; font-weight: 600; }
.instinctor-filter-list { list-style: none; margin: 0; padding: 0; }
.instinctor-filter-list li { margin-bottom: 8px; }
.instinctor-filter-list label { display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 14px; }
.instinctor-filter-list .count { color: #999; font-size: 12px; }
.instinctor-price-range { display: flex; gap: 10px; align-items: center; }
.instinctor-price-range input { width: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
.instinctor-price-slider { margin-top: 15px; }
.instinctor-price-slider input { width: 100%; }
.instinctor-rating-filter label { color: #f5a623; }

.instinctor-products-main { }
.instinctor-products-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.instinctor-sort-wrapper { display: flex; align-items: center; gap: 10px; }
#instinctor-sort { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; }

.instinctor-products-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
.instinctor-product-card { background: #fff; border: 1px solid #eee; border-radius: 8px; overflow: hidden; transition: box-shadow 0.2s; }
.instinctor-product-card:hover { box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
.instinctor-product-card-image { aspect-ratio: 1; background: #f9f9f9; position: relative; }
.instinctor-product-card-image img { width: 100%; height: 100%; object-fit: cover; }
.instinctor-product-card-badge { position: absolute; top: 10px; left: 10px; background: #e53935; color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; }

.instinctor-product-card-content { padding: 15px; }
.instinctor-product-card-title { margin: 0 0 8px; font-size: 15px; font-weight: 500; }
.instinctor-product-card-title a { color: inherit; text-decoration: none; }
.instinctor-product-card-price { font-size: 16px; font-weight: 600; }
.instinctor-product-card-price .sale { color: #e53935; }
.instinctor-product-card-price .original { text-decoration: line-through; color: #999; margin-left: 8px; font-weight: normal; }
.instinctor-product-card-rating { margin-top: 8px; color: #f5a623; font-size: 13px; }

.instinctor-loading { text-align: center; padding: 40px; color: #666; }
.instinctor-spinner { width: 30px; height: 30px; border: 3px solid #eee; border-top-color: #1d1d1f; border-radius: 50%; animation: spin 0.8s linear infinite; margin: 0 auto 10px; }
@keyframes spin { to { transform: rotate(360deg); } }

.instinctor-pagination { display: flex; justify-content: center; gap: 5px; margin-top: 30px; }
.instinctor-pagination button { padding: 10px 15px; border: 1px solid #ddd; background: #fff; cursor: pointer; border-radius: 4px; }
.instinctor-pagination button.active { background: #1d1d1f; color: #fff; border-color: #1d1d1f; }
.instinctor-pagination button:disabled { opacity: 0.5; cursor: not-allowed; }

.instinctor-no-results { text-align: center; padding: 60px 20px; color: #666; }

@media (max-width: 900px) {
    .instinctor-filter-layout { grid-template-columns: 1fr; }
    .instinctor-filters-sidebar { position: static; }
    .instinctor-products-grid { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 500px) {
    .instinctor-products-grid { grid-template-columns: 1fr; }
}
<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>

<?php ob_start(); ?>
(function() {
    const nonce = '<?php echo esc_js( wp_create_nonce('instinctor_search') ); ?>';
    let currentPage = 1;
    let searchTimeout;
    let currentFilters = {};

    // Initialize
    loadProducts();

    // Search input
    const searchInput = document.getElementById('instinctor-search-input');
    const autocomplete = document.getElementById('instinctor-autocomplete');
    const clearBtn = document.getElementById('instinctor-search-clear');

    searchInput.addEventListener('input', function() {
        clearBtn.style.display = this.value ? 'block' : 'none';
        
        clearTimeout(searchTimeout);
        
        if (this.value.length >= 2) {
            searchTimeout = setTimeout(() => showAutocomplete(this.value), 200);
        } else {
            autocomplete.style.display = 'none';
        }
    });

    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            autocomplete.style.display = 'none';
            currentPage = 1;
            loadProducts();
        }
    });

    clearBtn.addEventListener('click', function() {
        searchInput.value = '';
        clearBtn.style.display = 'none';
        autocomplete.style.display = 'none';
        currentPage = 1;
        loadProducts();
    });

    // Autocomplete
    function showAutocomplete(query) {
        fetch(instinctorFrontend.ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=instinctor_autocomplete&nonce=${nonce}&query=${encodeURIComponent(query)}`
        })
        .then(r => r.json())
        .then(data => {
            if (data.success && data.data.length) {
                autocomplete.innerHTML = data.data.map(p => `
                    <a href="${p.url}" class="instinctor-autocomplete-item">
                        <img src="${p.image_url || ''}" alt="">
                        <div class="instinctor-autocomplete-item-info">
                            <div class="instinctor-autocomplete-item-name">${p.name}</div>
                            <div class="instinctor-autocomplete-item-price">${p.formatted_price}</div>
                        </div>
                    </a>
                `).join('');
                autocomplete.style.display = 'block';
            } else {
                autocomplete.style.display = 'none';
            }
        });
    }

    // Close autocomplete on click outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.instinctor-search-bar')) {
            autocomplete.style.display = 'none';
        }
    });

    // Filter changes
    document.querySelectorAll('.instinctor-filters-sidebar input, .instinctor-filters-sidebar select').forEach(el => {
        el.addEventListener('change', () => {
            currentPage = 1;
            loadProducts();
        });
    });

    // Price inputs
    ['instinctor-min-price', 'instinctor-max-price'].forEach(id => {
        document.getElementById(id)?.addEventListener('change', () => {
            currentPage = 1;
            loadProducts();
        });
    });

    // Sort
    document.getElementById('instinctor-sort').addEventListener('change', () => {
        currentPage = 1;
        loadProducts();
    });

    // Clear filters
    document.getElementById('instinctor-clear-filters').addEventListener('click', () => {
        document.querySelectorAll('.instinctor-filters-sidebar input[type="checkbox"]').forEach(cb => cb.checked = false);
        document.querySelectorAll('.instinctor-filters-sidebar input[type="radio"]').forEach(r => r.checked = false);
        document.getElementById('instinctor-min-price').value = '';
        document.getElementById('instinctor-max-price').value = '';
        document.getElementById('instinctor-sort').value = 'newest';
        searchInput.value = '';
        currentPage = 1;
        loadProducts();
    });

    // Load products
    function loadProducts() {
        const filters = {
            query: searchInput.value,
            category: [...document.querySelectorAll('input[name="category"]:checked')].map(cb => cb.value).join(','),
            min_price: document.getElementById('instinctor-min-price').value,
            max_price: document.getElementById('instinctor-max-price').value,
            min_rating: document.querySelector('input[name="min_rating"]:checked')?.value || '',
            in_stock: document.getElementById('instinctor-in-stock').checked ? 1 : 0,
            on_sale: document.getElementById('instinctor-on-sale').checked ? 1 : 0,
            sort: document.getElementById('instinctor-sort').value,
            page: currentPage
        };

        document.getElementById('instinctor-loading').style.display = 'block';
        document.getElementById('instinctor-products-grid').style.opacity = '0.5';

        const params = new URLSearchParams({ action: 'instinctor_search_products', nonce, ...filters });

        fetch(instinctorFrontend.ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('instinctor-loading').style.display = 'none';
            document.getElementById('instinctor-products-grid').style.opacity = '1';

            if (data.success) {
                renderProducts(data.data.products);
                renderPagination(data.data.pages, data.data.total);
                document.getElementById('instinctor-results-count').textContent = data.data.total;
            }
        });
    }

    // Render products
    function renderProducts(products) {
        const grid = document.getElementById('instinctor-products-grid');
        
        if (!products.length) {
            grid.innerHTML = '<div class="instinctor-no-results">No products found matching your criteria.</div>';
            return;
        }

        grid.innerHTML = products.map(p => `
            <div class="instinctor-product-card">
                <div class="instinctor-product-card-image">
                    ${p.image_url ? `<img src="${p.image_url}" alt="${p.name}">` : ''}
                    ${p.sale_price ? '<span class="instinctor-product-card-badge">Sale</span>' : ''}
                </div>
                <div class="instinctor-product-card-content">
                    <h3 class="instinctor-product-card-title"><a href="/product/${p.slug}">${p.name}</a></h3>
                    <div class="instinctor-product-card-price">
                        ${p.sale_price ? `<span class="sale">${formatPrice(p.sale_price)}</span><span class="original">${formatPrice(p.price)}</span>` : formatPrice(p.price)}
                    </div>
                </div>
            </div>
        `).join('');        });
    }

    // Render pagination
    function renderPagination(totalPages, total) {
        const pagination = document.getElementById('instinctor-pagination');
        
        if (totalPages <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let html = '';
        
        html += `<button ${currentPage === 1 ? 'disabled' : ''} data-page="${currentPage - 1}">←</button>`;
        
        for (let i = 1; i <= Math.min(totalPages, 5); i++) {
            html += `<button class="${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`;
        }
        
        if (totalPages > 5) {
            html += '<span>...</span>';
            html += `<button data-page="${totalPages}">${totalPages}</button>`;
        }
        
        html += `<button ${currentPage === totalPages ? 'disabled' : ''} data-page="${currentPage + 1}">→</button>`;

        pagination.innerHTML = html;

        pagination.querySelectorAll('button').forEach(btn => {
            btn.addEventListener('click', function() {
                currentPage = parseInt(this.dataset.page);
                loadProducts();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
        });
    }

    // Format price helper
    function formatPrice(price) {
        return '$' + parseFloat(price).toFixed(2);
    }
})();
<?php $_inst_ljs = ob_get_clean(); wp_add_inline_script('instinctor-frontend-js', $_inst_ljs, 'after'); ?>
