<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Browse Items - LocalLendables</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #28a745;
            --secondary-color: #20c997;
        }
        
        .item-card {
            transition: transform 0.2s ease;
            cursor: pointer;
        }
        
        .item-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .badge-free {
            background-color: var(--secondary-color) !important;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container">
            <a class="navbar-brand text-success fw-bold" href="/dashboard/{{ currentUser.id }}">Local Lendables</a>
            <div class="navbar-nav ms-auto">
                <a href="/dashboard/{{ currentUser.id }}" class="btn btn-outline-success btn-sm">
                    <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <div class="row mb-4">
            <div class="col-12">
                <h1 class="h3 text-success mb-3">Browse Available Items</h1>
                <p class="text-muted">Discover items shared by your community members</p>
            </div>
        </div>

        <div class="row g-4" id="itemsGrid">
            {% for item in items %}
            <div class="col-lg-4 col-md-6">
                <div class="card item-card h-100" onclick="openItemModal(
                    {{ item.id }}, 
                    '{{ item.title|e('js') }}', 
                    '{{ item.description|e('js') }}', 
                    '{{ item.category|e('js') }}', 
                    '{{ item.condition|e('js') }}', 
                    '{{ item.primaryLogo ?: item.imageUrl|e('js') }}', 
                    '{{ item.extraImages|e('js') }}', 
                    '{{ item.dailyRate|e('js') }}', 
                    '{{ item.ownerShowName|e('js') }}', 
                    '{{ item.ownerAvatar|e('js') }}', 
                    '{{ item.ownerRating|e('js') }}'
                )">
                    <div class="position-relative">
                        <img src="/lendable_items/{{ item.thumbnailLogo ?: item.imageUrl }}" 
                             class="card-img-top" 
                             alt="{{ item.title }}" 
                             style="height: 200px; object-fit: contain; padding: 10px;">
                        <div class="position-absolute top-0 end-0 m-2">
                            {% if item.isRequest %}
                                <span class="badge bg-info">Request</span>
                            {% elseif item.dailyRate == "0.00" %}
                                <span class="badge badge-free">Free</span>
                            {% else %}
                                <span class="badge bg-primary">${{ item.dailyRate }}/day</span>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="card-body">
                        {% if item.isRequest %}
                            <div class="d-flex align-items-center mb-2">
                                <span class="small text-muted">Asking For:</span>
                            </div>
                        {% endif %}
                        <h5 class="card-title text-success mb-2">{{ item.title }}{% if item.isRequest %}?{% endif %}</h5>
                        <p class="card-text text-muted small mb-2">{{ item.category }}</p>
                        <p class="card-text">{{ item.description|length > 80 ? item.description|slice(0, 80) ~ '...' : item.description }}</p>
                        
                        <div class="d-flex align-items-center mt-auto">
                            <img src="/ll_images/{{ item.ownerAvatar }}" 
                                 class="rounded-circle me-2" 
                                 width="30" height="30">
                            <div>
                                <div class="fw-bold small">{{ item.ownerShowName }}</div>
                                <div class="text-muted small">{{ item.ownerRating }} ⭐</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Item Detail Modal -->
    <div class="modal fade" id="itemDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="itemModalTitle">Item Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div id="itemModalCarousel" class="carousel slide" data-bs-ride="carousel">
                                <div class="carousel-inner" id="carouselImages">
                                    <!-- Images populated by JavaScript -->
                                </div>
                                <div id="carouselControls" style="display: none;">
                                    <button class="carousel-control-prev" type="button" data-bs-target="#itemModalCarousel" data-bs-slide="prev">
                                        <span class="carousel-control-prev-icon"></span>
                                    </button>
                                    <button class="carousel-control-next" type="button" data-bs-target="#itemModalCarousel" data-bs-slide="next">
                                        <span class="carousel-control-next-icon"></span>
                                    </button>
                                    <div class="carousel-indicators" id="carouselIndicators"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <span class="badge bg-secondary" id="itemModalCategory">Category</span>
                                <span class="badge bg-warning text-dark ms-2" id="itemModalCondition">Condition</span>
                            </div>
                            
                            <h6 class="text-primary mb-3" id="itemModalPrice">Price</h6>
                            <p class="text-muted mb-4" id="itemModalDescription">Description</p>
                            
                            <div class="d-flex align-items-center mb-4 p-3 bg-light rounded">
                                <img id="itemModalOwnerAvatar" src="" class="rounded-circle me-3" width="40" height="40">
                                <div>
                                    <div class="fw-bold" id="itemModalOwnerName">Owner</div>
                                    <div class="text-muted small">
                                        <span id="itemModalOwnerRating">5.0</span> ⭐ rating
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-grid">
                                <button class="btn btn-success" onclick="requestItemFromModal()">
                                    <i class="fas fa-hand-holding me-2"></i>Request to Borrow
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    let currentItemId = null;

    function openItemModal(itemId, title, description, category, condition, primaryImage, extraImages, dailyRate, ownerName, ownerAvatar, ownerRating) {
        currentItemId = itemId;
        
        // Set modal content
        document.getElementById('itemModalTitle').textContent = title;
        document.getElementById('itemModalCategory').textContent = category;
        document.getElementById('itemModalCondition').textContent = condition.charAt(0).toUpperCase() + condition.slice(1);
        document.getElementById('itemModalPrice').textContent = dailyRate === '0.00' ? 'Lendable' : '$' + dailyRate + '/day';
        document.getElementById('itemModalDescription').textContent = description;
        document.getElementById('itemModalOwnerName').textContent = ownerName;
        document.getElementById('itemModalOwnerAvatar').src = '/ll_images/' + ownerAvatar;
        document.getElementById('itemModalOwnerRating').textContent = ownerRating;
        
        // Build image gallery
        const carouselImages = document.getElementById('carouselImages');
        const carouselIndicators = document.getElementById('carouselIndicators');
        const carouselControls = document.getElementById('carouselControls');
        
        // Clear existing content
        carouselImages.innerHTML = '';
        carouselIndicators.innerHTML = '';
        
        // Prepare image list
        const images = [primaryImage];
        if (extraImages && extraImages.trim() && extraImages !== 'null') {
            const additionalImages = extraImages.split(',').map(img => img.trim()).filter(img => img);
            images.push(...additionalImages);
        }
        
        // Create carousel items and indicators
        images.forEach((image, index) => {
            // Create carousel item
            const carouselItem = document.createElement('div');
            carouselItem.className = 'carousel-item' + (index === 0 ? ' active' : '');
            carouselItem.innerHTML = `
                <img src="/lendable_items/${image}" 
                     class="d-block w-100" 
                     alt="${title}"
                     style="height: 400px; object-fit: contain; border-radius: 8px; background: #f8f9fa;">
            `;
            carouselImages.appendChild(carouselItem);
            
            // Create indicator
            const indicator = document.createElement('button');
            indicator.type = 'button';
            indicator.setAttribute('data-bs-target', '#itemModalCarousel');
            indicator.setAttribute('data-bs-slide-to', index.toString());
            if (index === 0) indicator.className = 'active';
            carouselIndicators.appendChild(indicator);
        });
        
        // Show/hide carousel controls based on number of images
        if (images.length > 1) {
            carouselControls.style.display = 'block';
        } else {
            carouselControls.style.display = 'none';
        }
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('itemDetailModal'));
        modal.show();
        
        // Track item view
        fetch(`/api/items/${itemId}/view`, {
            method: 'POST'
        }).catch(error => console.log('View tracking failed:', error));
    }

    function requestItemFromModal() {
        if (currentItemId) {
            alert('Request feature coming soon! You would request item ID: ' + currentItemId);
        }
    }
    </script>
</body>
</html>