@extends('layouts.app')

@section('title', 'Products')

@section('content')
<div class="container mx-auto px-4 py-8">
    <x-breadcrumbs :items="[
        ['label' => 'Home', 'url' => route('home')],
        ['label' => 'Products']
    ]" />
    <div class="flex flex-col md:flex-row gap-8">
        <!-- Filters Sidebar -->
        <aside class="w-full md:w-64">
            <div class="bg-white p-4 md:p-6 rounded-2xl shadow-md border border-[#e8ddd0] sticky top-20 md:top-24">
                <h3 class="text-lg md:text-xl font-serif font-bold mb-4 md:mb-6 text-[#524438]">Filters</h3>
                
                <form method="GET" action="{{ route('products.index') }}" id="filter-form" data-ajax-form>
                    <!-- Search -->
                    <div class="mb-5">
                        <label class="block text-sm font-semibold mb-2 text-[#645443]">Search</label>
                        <input type="text" name="search" value="{{ request('search') }}" placeholder="Search products..." 
                            class="w-full px-3 md:px-4 py-2 md:py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] text-sm md:text-base">
                    </div>
                    
                    <!-- Category -->
                    <div class="mb-5">
                        <label class="block text-sm font-semibold mb-2 text-[#645443]">Category</label>
                        <select name="category" 
                            class="w-full px-3 md:px-4 py-2 md:py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] bg-white text-sm md:text-base">
                            <option value="">All Categories</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{ (string)request('category') === (string)$category->id ? 'selected' : '' }}>
                                    {{ $category->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    <!-- Price Range -->
                    <div class="mb-5">
                        <label class="block text-sm font-semibold mb-2 text-[#645443]">Price Range</label>
                        <div class="flex gap-2">
                            <input type="number" name="min_price" value="{{ request('min_price') }}" placeholder="Min" 
                                class="w-full px-3 md:px-4 py-2 md:py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] text-sm md:text-base">
                            <input type="number" name="max_price" value="{{ request('max_price') }}" placeholder="Max" 
                                class="w-full px-3 md:px-4 py-2 md:py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] text-sm md:text-base">
                        </div>
                    </div>
                    
                    <!-- Sort -->
                    <div class="mb-5">
                        <label class="block text-sm font-semibold mb-2 text-[#645443]">Sort By</label>
                        <select name="sort" 
                            class="w-full px-4 py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] bg-white mb-2">
                            <option value="name" {{ request('sort') == 'name' ? 'selected' : '' }}>Name</option>
                            <option value="price" {{ request('sort') == 'price' ? 'selected' : '' }}>Price</option>
                            <option value="created_at" {{ request('sort') == 'created_at' ? 'selected' : '' }}>Newest</option>
                        </select>
                        <select name="direction" 
                            class="w-full px-4 py-2.5 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] bg-white">
                            <option value="asc" {{ request('direction') == 'asc' ? 'selected' : '' }}>Ascending</option>
                            <option value="desc" {{ request('direction') == 'desc' ? 'selected' : '' }}>Descending</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="w-full bg-[#7d6a52] text-white px-6 py-3 rounded-full hover:bg-[#9d8566] transition-all font-semibold shadow-lg hover:shadow-xl transform hover:scale-105">
                        Apply Filters
                    </button>
                    <a href="{{ route('products.index') }}" class="block text-center mt-3 text-[#9d8566] hover:text-[#7d6a52] transition-colors font-medium">
                        Clear Filters
                    </a>
                </form>
            </div>
        </aside>
        
        <!-- Products Grid -->
        <div class="flex-1" id="products-container">
            @include('products.partials.product-grid', ['products' => $products])
        </div>
    </div>
</div>
@endsection

@push('modals')
<!-- Quick View Modal -->
<div id="quick-view-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden z-50 flex items-center justify-center p-4 animate-fadeIn">
    <div class="bg-white rounded-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto shadow-2xl border border-[#e8ddd0] animate-slideUp">
        <div class="flex items-center justify-between p-6 border-b border-[#e8ddd0] bg-gradient-to-r from-[#faf8f5] to-white">
            <h3 class="text-2xl font-serif font-bold text-[#524438]">Quick View</h3>
            <button onclick="closeModal('quick-view-modal')" class="text-[#9d8566] hover:text-[#7d6a52] transition-colors p-2 hover:bg-[#f5f0e8] rounded-full">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <div id="quick-view-content" class="p-6">
            <!-- Content loaded via AJAX -->
        </div>
    </div>
</div>
@endpush

@push('scripts')
<script>
function openQuickView(productId) {
    fetch(`/products/${productId}/quick-view`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('quick-view-content').innerHTML = data.html;
            openModal('quick-view-modal');
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading product details');
        });
}

// AJAX Filter Form
document.addEventListener('DOMContentLoaded', function() {
    const filterForm = document.getElementById('filter-form');
    const productsContainer = document.getElementById('products-container');
    let filterTimeout;
    
    // Handle form submission with AJAX
    filterForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        applyFilters();
    });
    
    // Auto-apply filters on input change (with debounce)
    const filterInputs = filterForm?.querySelectorAll('input, select');
    filterInputs?.forEach(input => {
        // For selects (category, sort, direction), apply immediately on change
        if (input.tagName === 'SELECT') {
            input.addEventListener('change', function() {
                clearTimeout(filterTimeout);
                filterTimeout = setTimeout(() => {
                    applyFilters();
                }, 300);
            });
        }
        
        // For number inputs (price), apply with debounce
        if (input.type === 'number') {
            input.addEventListener('change', function() {
                clearTimeout(filterTimeout);
                filterTimeout = setTimeout(() => {
                    applyFilters();
                }, 500);
            });
        }
        
        // For text inputs, use input event for real-time search
        if (input.type === 'text') {
            input.addEventListener('input', function() {
                clearTimeout(filterTimeout);
                filterTimeout = setTimeout(() => {
                    applyFilters();
                }, 800);
            });
        }
    });
    
    function applyFilters() {
        const formData = new FormData(filterForm);
        const params = new URLSearchParams(formData);
        
        // Show loading skeleton
        productsContainer.innerHTML = `
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                ${showProductSkeletons(6)}
            </div>
        `;
        
        // Update URL without page reload
        const url = new URL(window.location.href);
        url.search = params.toString();
        window.history.pushState({}, '', url);
        
        // Fetch products via AJAX
        fetch(`{{ route('products.index') }}?${params.toString()}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            productsContainer.innerHTML = data.html + data.pagination;
            
            // Scroll to top of products
            productsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        })
        .catch(error => {
            console.error('Error:', error);
            productsContainer.innerHTML = '<div class="bg-white p-8 rounded-lg shadow-md text-center"><p class="text-red-500">Error loading products. Please try again.</p></div>';
        });
    }
    
    // Handle pagination links with AJAX
    document.addEventListener('click', function(e) {
        if (e.target.closest('.pagination a')) {
            e.preventDefault();
            const url = e.target.closest('a').href;
            
            productsContainer.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    ${showProductSkeletons(6)}
                </div>
            `;
            
            fetch(url, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                productsContainer.innerHTML = data.html + data.pagination;
                window.scrollTo({ top: 0, behavior: 'smooth' });
            })
            .catch(error => {
                console.error('Error:', error);
                window.location.href = url; // Fallback to normal navigation
            });
        }
    });
});
</script>
@endpush

