{% extends "layout.html.twig" %}

{% block title %}Browse All Lendables - Local Lendables{% endblock %}

{% block content %}
<style>
    html {
        scroll-behavior: smooth;
    }
</style>


<main class="content-wrapper">
    <!-- Breadcrumb handled by layout template -->

    <section class="container pt-1 mt-1 mt-sm-3">
        <div class="row">
            <div class="col-12 col-md-8 col-lg-8 col-xl-8 col-xxl-8 border rounded-4 pt-2 px-2">
                <div class="d-flex align-items-center mb-2">
                    <img src="/lendables/logo_browse_600.png" alt="Browse Lendables" style="max-width: 100px; height: auto;" class="me-3">
                    <div>
                        <span class="giantish">Lendables, Requests & Hours:</span>
                        <br>
                        <span class="small text-muted" style="line-height: 1.0 !important; display: block;">Use the <b>many filters and sorting options</b> to find what you want. Search itself is above, in the header.</span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-4 col-lg-4 col-xl-4 col-xxl-4 border rounded-4 pt-2 px-2">
                <h6>Quick Stats</h6>
                <p class="small text-muted mb-1">Total Items: {{ totalItems }}</p>
                <p class="small text-muted mb-1">
                    {% if hourOfferings|default([])|length > 0 %}
                        <a href="#first-hour-offer" class="text-decoration-none text-muted">Hour Offers: {{ hourOfferings|default([])|length }}</a>
                    {% else %}
                        Hour Offers: {{ hourOfferings|default([])|length }}
                    {% endif %}
                </p>
                <p class="small text-muted mb-1">Items Shown: <span id="items-shown">{{ (items|length) + (hourOfferings|default([])|length) }}</span></p>
                <p class="small text-muted mb-1">Active Members: {{ totalMembers }}</p>
            </div>
        </div>
    </section>

    <section class="container pt-1 mt-1 mt-sm-3">
        <div class="row">
            <div class="col-12">
                <!-- Filters Section -->
                <div class="mb-3">
                    <!-- Sorting Buttons -->
                    {% set itemCount = items|length %}
                    {% if selectedFilter == 'my-favorites' or selectedFilter == 'my-chats' %}
                        {% if itemCount < 3 %}
                            <a href="/browse?sort=alphabetic&category=all&filter=all" 
                               class="btn btn-sm me-2 btn-outline-primary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">ALPHABETIC</a>
                            <a href="/browse?sort=newest&category=all&filter=all" 
                               class="btn btn-sm me-2 btn-outline-success" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">NEWEST</a>
                            <a href="/browse?sort=random&category=all&filter=all" 
                               class="btn btn-sm me-2 btn-outline-secondary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">RANDOM BROWSE</a>
                        {% else %}
                            <a href="javascript:void(0)" onclick="sortCurrentItems('alphabetic')"
                               class="btn btn-sm me-2 {{ selectedSort == 'alphabetic' ? 'btn-primary' : 'btn-outline-primary' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">ALPHABETIC</a>
                            <a href="javascript:void(0)" onclick="sortCurrentItems('newest')"
                               class="btn btn-sm me-2 {{ selectedSort == 'newest' ? 'btn-success' : 'btn-outline-success' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">NEWEST</a>
                            <a href="javascript:void(0)" onclick="sortCurrentItems('random')"
                               class="btn btn-sm me-2 {{ selectedSort == 'random' ? 'btn-dark' : 'btn-outline-secondary' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">RANDOM BROWSE</a>
                        {% endif %}
                    {% else %}
                        <a href="/browse?sort=alphabetic&category={{ selectedCategory|url_encode }}&filter={{ selectedFilter }}" 
                           class="btn btn-sm me-2 {{ selectedSort == 'alphabetic' ? 'btn-primary' : 'btn-outline-primary' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">ALPHABETIC</a>
                        <a href="/browse?sort=newest&category={{ selectedCategory|url_encode }}&filter={{ selectedFilter }}" 
                           class="btn btn-sm me-2 {{ selectedSort == 'newest' ? 'btn-success' : 'btn-outline-success' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">NEWEST</a>
                        <a href="/browse?sort=random&category={{ selectedCategory|url_encode }}&filter={{ selectedFilter }}" 
                           class="btn btn-sm me-2 {{ selectedSort == 'random' ? 'btn-dark' : 'btn-outline-secondary' }}" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">RANDOM BROWSE</a>
                    {% endif %}
                    
                    <!-- Categories Dropdown -->
                    <div class="dropdown d-inline-block me-2">
                        <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">
                            CATEGORIES
                        </button>
                        <ul class="dropdown-menu">
                            {% if selectedFilter == 'my-favorites' or selectedFilter == 'my-chats' %}
                                <li><a class="dropdown-item" 
                                       href="/browse?sort={{ selectedSort }}&category=all&filter=all">All Categories</a></li>
                                {% for category in categories %}
                                <li><a class="dropdown-item" 
                                       href="/browse?sort={{ selectedSort }}&category={{ category|url_encode }}&filter=all">{{ category }}</a></li>
                                {% endfor %}
                            {% else %}
                                <li><a class="dropdown-item {{ selectedCategory == 'all' ? 'active' : '' }}" 
                                       href="/browse?sort={{ selectedSort }}&category=all&filter={{ selectedFilter }}">All Categories</a></li>
                                {% for category in categories %}
                                <li><a class="dropdown-item {{ selectedCategory == category ? 'active' : '' }}" 
                                       href="/browse?sort={{ selectedSort }}&category={{ category|url_encode }}&filter={{ selectedFilter }}">{{ category }}</a></li>
                                {% endfor %}
                            {% endif %}
                        </ul>
                    </div>

                    {% if currentUser %}
                    <!-- Personal Filters Dropdown -->
                    <div class="dropdown d-inline-block me-2">
                        <button class="btn btn-sm btn-outline-info dropdown-toggle" type="button" data-bs-toggle="dropdown" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">
                            MY FILTERS
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item {{ selectedFilter == 'all' ? 'active' : '' }}" 
                                   href="/browse?sort={{ selectedSort }}&category=all&filter=all">All Items</a></li>
                            <li><a class="dropdown-item {{ selectedFilter == 'my-chats' ? 'active' : '' }}" 
                                   href="/browse?sort={{ selectedSort }}&category=all&filter=my-chats">
                                   <i class="fas fa-comments me-2"></i>Items I'm Chatting About</a></li>
                            <li><a class="dropdown-item {{ selectedFilter == 'my-favorites' ? 'active' : '' }}" 
                                   href="/browse?sort={{ selectedSort }}&category=all&filter=my-favorites">
                                   <i class="fas fa-heart me-2"></i>My Favorites</a></li>
                        </ul>
                    </div>
                    {% endif %}

                </div>

                <!-- Current Filter/Category Display -->
                {% if selectedCategory != 'all' or selectedFilter != 'all' %}
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="alert alert-info d-flex align-items-center justify-content-between" style="margin-bottom: 1rem;">
                            <div class="d-flex align-items-center">
                                {% if selectedFilter == 'my-favorites' %}
                                    <i class="fas fa-heart me-2"></i>
                                    <strong>My Favorites</strong>
                                {% elseif selectedFilter == 'my-chats' %}
                                    <i class="fas fa-comments me-2"></i>
                                    <strong>Items I'm Chatting About</strong>
                                {% elseif selectedCategory != 'all' %}
                                    <i class="fas fa-tag me-2"></i>
                                    <strong>Category: {{ selectedCategory }}</strong>
                                {% endif %}
                                <span class="text-muted ms-2">({{ (items|length) + (hourOfferings|default([])|length) }} items{% if (hourOfferings|default([])|length) > 0 %} & offerings{% endif %})</span>
                            </div>
                            {% if selectedCategory != 'all' %}
                                <a href="/browse?sort={{ selectedSort }}&category=all&filter={{ selectedFilter }}" 
                                   class="btn btn-sm btn-outline-primary" 
                                   style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">DISPLAY<br>ALL</a>
                            {% endif %}
                        </div>
                    </div>
                </div>
                {% endif %}

                <!-- Items and Hour Offerings Cards -->
                <div class="row g-3">
                    {% set combinedItems = [] %}
                    {% for item in items %}
                        {% set combinedItems = combinedItems|merge([item|merge({'type': 'item'})]) %}
                    {% endfor %}
                    {% for offering in hourOfferings|default([]) %}
                        {% set combinedItems = combinedItems|merge([offering|merge({'type': 'hour_offering'})]) %}
                    {% endfor %}
                    
                    {% if combinedItems|length > 0 %}
                        {% for item in combinedItems %}
                        {% set itemColClass = (selectedSort == 'random' or (selectedCategory != 'all' and selectedCategory != '')) ? 'col-12 col-sm-6' : 'col-12' %}
                        <div class="{{ itemColClass }}">
                            {% if item.type == 'hour_offering' %}
                                <!-- Hour Offering Card -->
                                <div {% if loop.first and loop.parent.loop.first %}id="first-hour-offer"{% endif %} class="card shadow-sm item-card" style="border-top: 2px solid #17a2b8; border-left: none; border-right: none; border-bottom: 1px solid #ddd; cursor: pointer; background-color: #e8f7fa;" 
                                     onclick="openContactHelperModal('{{ item.userId }}', '{{ item.id }}', '{{ item.offerUserShowName ?: item.offerUserFirstName }}', '{{ item.title }}')"
                                     onmouseover="this.style.backgroundColor='#b2ebf2'"
                                     onmouseout="this.style.backgroundColor='#e8f7fa'">
                                    <div class="card-body p-2" style="position: relative;">
                                        
                                        <!-- Top Row: Member Avatar, Hours Icon, Contact Button -->
                                        <div class="row align-items-center mb-2 gx-1">
                                            <!-- Member Avatar (25% width) -->
                                            <div class="col-3 text-center">
                                                <a href="/dashboard/{{ item.userId }}" class="text-decoration-none tooltip-enhanced" 
                                                   title="{{ item.offerUserShowName ?: item.offerUserFirstName }}">
                                                    <img src="/ll_images/{{ item.offerUserAvatar }}" 
                                                         alt="{{ item.offerUserShowName ?: item.offerUserFirstName }}" 
                                                         class="rounded-circle d-block mx-auto mb-1" 
                                                         style="width: 80%; max-width: 80px; height: auto; aspect-ratio: 1; object-fit: cover; border: 1px solid #ddd;"
                                                         onerror="this.src='/avatars/default.svg'">
                                                </a>
                                                <div class="text-info fw-medium" style="font-size: 0.7rem;">
                                                    {{ item.offerUserShowName ?: item.offerUserFirstName }}
                                                </div>
                                            </div>
                                        
                                            <!-- Hours On Offer Icon (25% width) -->
                                            <div class="col-3 text-center">
                                                <img src="/lendables/logo_hoursoffered_600.png" 
                                                     alt="Offered Hour" 
                                                     style="width: 120%; max-width: 96px; height: auto; object-fit: contain;">
                                            </div>
                                            
                                            <!-- Schedule Button (50% width) -->
                                            <div class="col-6 text-center">
                                                <a href="/browse-hours?user={{ item.userId }}&offering={{ item.id }}" class="text-decoration-none tooltip-enhanced" title="Schedule this hour offering">
                                                    <div class="d-inline-block position-relative" style="width: 60px; height: 50px;">
                                                        <!-- Mini Calendar Background -->
                                                        <div class="border border-2 border-dark rounded" 
                                                             style="width: 60px; height: 50px; background-color: white; position: relative;">
                                                            <!-- Calendar Header -->
                                                            <div class="bg-secondary text-white text-center rounded-top" 
                                                                 style="height: 12px; line-height: 12px; font-size: 0.6rem; font-weight: bold;">
                                                                {{ item.offerDate|date('M') }}
                                                            </div>
                                                            <!-- Calendar Date -->
                                                            <div class="text-center" 
                                                                 style="height: 38px; line-height: 38px; font-size: 1.2rem; font-weight: bold; color: #28a745;">
                                                                {{ item.offerDate|date('j') }}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                        </div>
                                        
                                        <!-- Bottom Row: Title, Date, Description -->
                                        <div class="row">
                                            <div class="col-12">
                                                <!-- Hour Offering Title -->
                                                <h6 class="mb-1 text-dark fw-bold" style="line-height: 1.0;">
                                                    {{ item.title }}
                                                </h6>
                                                
                                                <!-- Description -->
                                                {% if item.description %}
                                                    <h6 class="mb-1 text-dark" style="line-height: 1.0; font-weight: normal;">
                                                        {{ item.description }}
                                                    </h6>
                                                {% endif %}
                                                
                                                <!-- Date and Time -->
                                                <div class="d-flex align-items-center mb-1">
                                                    <span class="badge bg-info me-2">Offered Hour</span>
                                                </div>
                                                
                                                <div class="small text-muted mb-1">
                                                    <strong>{{ item.offerDate|date('l, F j, Y') }}</strong>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            {% else %}
                                <!-- Regular Item Card -->
                                <div class="card shadow-sm item-card" style="border-top: 2px solid {% if item.isRequest %}#ffc107{% else %}#28a745{% endif %}; border-left: none; border-right: none; border-bottom: 1px solid #ddd; cursor: pointer; background-color: {% if item.isRequest %}#fff8e1{% else %}#ffffff{% endif %};" 
                                     onclick="navigateToItem({{ item.id }}, event)"
                                     onmouseover="this.style.backgroundColor='{% if currentUser and item.owner == currentUser.id %}#fce4ec{% elseif item.isRequest %}#fff3cd{% else %}#d4edda{% endif %}'"
                                     onmouseout="this.style.backgroundColor='{% if item.isRequest %}#fff8e1{% else %}white{% endif %}'">
                                    <div class="card-body p-2" style="position: relative;">
                                    
                                    <!-- Top Row: Image, Avatar+Name, Borrow, Chat -->
                                    <div class="row align-items-center mb-2 gx-1">
                                        <!-- Item Image (25% width) -->
                                        <div class="col-3 text-center">
                                            {% if item.primaryLogo %}
                                                <img src="/lendable_items/{{ item.thumbnailLogo ?: item.primaryLogo }}" 
                                                     class="img-fluid rounded" 
                                                     style="width: 100%; max-height: 120px; object-fit: contain; border: 1px solid #ddd;"
                                                     alt="{{ item.name }}"
                                                     onerror="this.src='/lendable_items/default-placeholder.jpg'">
                                            {% else %}
                                                <div class="d-flex align-items-center justify-content-center rounded bg-light"
                                                     style="width: 100%; height: 120px; border: 1px solid #ddd; margin: 0 auto;">
                                                    <i class="fas fa-image text-muted" style="font-size: 1.5rem;"></i>
                                                </div>
                                            {% endif %}
                                        </div>
                                    
                                    <!-- Owner Avatar and Name (25% width - Stacked) -->
                                    <div class="col-3 text-center">
                                        {% if currentUser and item.owner == currentUser.id %}
                                            <a href="/dashboard/{{ item.owner }}" class="text-decoration-none tooltip-enhanced" 
                                               title="This is your item">
                                                <img src="/ll_images/{{ item.ownerAvatar }}" 
                                                     alt="Your Item" 
                                                     class="rounded-circle d-block mx-auto mb-1" 
                                                     style="width: 80%; max-width: 50px; height: auto; aspect-ratio: 1; object-fit: cover; border: 1px solid #ddd;"
                                                     onerror="this.src='/avatars/default.svg'">
                                                <div class="text-primary fw-medium" style="font-size: 0.8rem;">
                                                    Your<br>Item
                                                </div>
                                            </a>
                                        {% else %}
                                            <a href="/dashboard/{{ item.owner }}" class="text-decoration-none tooltip-enhanced" 
                                               title="{{ item.ownerShowName ?: (item.ownerFirstName ~ ' ' ~ item.ownerLastName) }}, has had {{ item.ownerLendablesCount|default(0) }} Lendables events.{% if item.ownerBio %} {{ item.ownerBio }}{% endif %}">
                                                <img src="/ll_images/{{ item.ownerAvatar }}" 
                                                     alt="{{ item.ownerShowName ?: item.ownerFirstName }}" 
                                                     class="rounded-circle d-block mx-auto mb-1" 
                                                     style="width: 80%; max-width: 50px; height: auto; aspect-ratio: 1; object-fit: cover; border: 1px solid #ddd;"
                                                     onerror="this.src='/avatars/default.svg'">
                                                <div class="text-primary fw-medium" style="font-size: 0.8rem;">
                                                    {% if item.ownerShowName %}{{ item.ownerShowName }}{% else %}{{ item.ownerFirstName }}{% endif %}
                                                </div>
                                            </a>
                                        {% endif %}
                                    </div>
                                    
                                    <!-- Action Buttons (50% width total - 25% each) -->
                                    {% if currentUser and item.owner == currentUser.id %}
                                        <!-- Edit Item Button for owned items -->
                                        <div class="col-6 text-start">
                                            <a href="/edit-item/{{ item.id }}" class="text-decoration-none tooltip-enhanced" title="Edit your item">
                                                <img src="/lendables/logo_edit_600.png" 
                                                     alt="Edit Item" 
                                                     style="max-width: 120px; height: auto;">
                                            </a>
                                        </div>
                                    {% else %}
                                        <!-- Borrow Button (25% width) -->
                                        <div class="col-3 text-center">
                                            {% if item.isRequest %}
                                                <span class="badge bg-info">Request</span>
                                            {% else %}
                                                <a href="/item/{{ item.id }}?calendar=open" class="text-decoration-none tooltip-enhanced" title="View calendar and request to borrow this item">
                                                    <img src="/lendables/logo_checkdates_600.png" 
                                                         alt="Calendar & Availability" 
                                                         style="max-width: 120px; height: auto;">
                                                </a>
                                            {% endif %}
                                        </div>
                                        
                                        <!-- Chat Button (25% width) -->
                                        <div class="col-3 text-center">
                                            {% if item.isRequest %}
                                                <a href="/item/{{ item.id }}#chat-section" 
                                                   class="text-decoration-none tooltip-enhanced" 
                                                   title="Chat with requester about this request">
                                                    <img src="/lendables/logo_chat2_600.png" 
                                                         alt="Respond to Request"
                                                         style="max-width: 120px; height: auto; object-fit: contain;">
                                                </a>
                                            {% else %}
                                                <a href="/item/{{ item.id }}#chat-section" class="text-decoration-none tooltip-enhanced" title="Chat with the Owner about the Item">
                                                    <img src="/lendables/logo_chat2_600.png" 
                                                         alt="Chat" 
                                                         style="max-width: 120px; height: auto;">
                                                </a>
                                            {% endif %}
                                        </div>
                                    {% endif %}
                                </div>
                                
                                <!-- Bottom Row: Status, Title, Category, Description (spans all columns) -->
                                <div class="row">
                                    <div class="col-12">

                                        
                                        <!-- Item Title -->
                                        {% if item.isRequest %}
                                            <div class="d-flex align-items-center mb-1">
                                                <div class="small text-muted">Asking For:</div>
                                            </div>
                                        {% endif %}
                                        <h6 class="mb-1" style="line-height: 1.0;">
                                            {% if currentUser and (item.owner == currentUser.id or isAdmin) %}
                                                <a class="text-success text-decoration-none fw-bold" 
                                                   href="/edit-item/{{ item.id }}">{{ item.name }}{% if item.isRequest %}?{% endif %}</a>
                                                {% if isAdmin and item.owner != currentUser.id %}
                                                    <a href="/edit-item/{{ item.id }}" class="badge bg-warning text-dark text-decoration-none ms-1" style="font-size: 0.5rem;" title="Click to edit as Admin">
                                                        <i class="fas fa-edit me-1"></i>ADMIN
                                                    </a>
                                                {% endif %}
                                            {% else %}
                                                <a class="text-success text-decoration-none fw-bold" 
                                                   href="/item/{{ item.id }}">{{ item.name }}{% if item.isRequest %}?{% endif %}</a>
                                            {% endif %}
                                        </h6>
                                        
                                        <!-- Category with Status Badges -->
                                        <div class="d-flex justify-content-between align-items-center text-muted mb-2" style="line-height: 1.0;">
                                            <div>
                                                <span class="small fw-medium">Category:</span> 
                                                <a href="/browse?sort=random&category={{ item.categoryName|url_encode }}&filter=all" 
                                                   class="text-primary small text-decoration-none"
                                                   onclick="event.stopPropagation();"
                                                   title="View all items in {{ item.categoryName ?: 'Uncategorized' }} category">{{ item.categoryName ?: 'Uncategorized' }}</a>
                                            </div>
                                            <!-- Status Badges - Flush Right -->
                                            <div class="d-flex align-items-center gap-2">
                                                {% if item.isRequest %}
                                                    <span class="badge bg-info badge-nowrap">Asking for...</span>
                                                    {% if item.urgency %}
                                                        {% if item.urgency == 'urgent' %}
                                                            <span class="badge bg-danger">Urgent</span>
                                                        {% elseif item.urgency == 'high' %}
                                                            <span class="badge bg-warning">High Priority</span>
                                                        {% endif %}
                                                    {% endif %}
                                                {% elseif item.pricePerDay and item.pricePerDay > 0 %}
                                                    <span class="badge bg-danger badge-nowrap">Rentable</span>
                                                    <div class="text-primary fw-bold">${{ item.pricePerDay }}/day</div>
                                                {% else %}
                                                    <span class="badge bg-success badge-nowrap">Lendable</span>
                                                {% endif %}
                                            </div>
                                        </div>
                                        
                                        <!-- Description -->
                                        {% if item.description %}
                                        <div class="text-muted medium">
                                            <span class="medium" style="font-family: Helvetica, Arial, sans-serif;">{{ item.description|slice(0, 150) }}{% if item.description|length > 150 %}...{% endif %}</span>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                                
                                <!-- Favorites Heart Button - Lower Right Corner -->
                                <div class="position-absolute bottom-0 end-0 p-2" style="z-index: 5;">
                                    <button class="btn btn-link p-0 border-0 favorite-btn" 
                                            data-item-id="{{ item.id }}" 
                                            data-user-id="{{ currentUser.id }}"
                                            title="Favorite me for later!"
                                            style="background: rgba(255,255,255,0.9); border-radius: 50%; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 8px rgba(0,0,0,0.2); cursor: pointer; pointer-events: auto;"
                                            onclick="handleFavoriteClick(event, {{ item.id }});">
                                        <i class="fas fa-heart" style="color: #ccc; font-size: 1.1rem; transition: color 0.3s; pointer-events: none;"></i>
                                    </button>
                                        </div>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                        {% endfor %}
                    {% else %}
                        <!-- Empty State Message -->
                        <div class="col-12 text-center" style="margin-top: 10px;">
                                    {% if selectedFilter == 'my-favorites' %}
                                        <div class="medium text-center text-muted">
                                            You have no Favorites to display right now.<br>
                                            Click the heart <i class="fas fa-heart text-danger"></i> in the lower right of<br>
                                            <a href="/browse?sort=random&category=all&filter=all" class="text-decoration-none text-primary">Lendable Listings</a> to return to them later!
                                    {% elseif selectedFilter == 'my-chats' %}
                                        <i class="fas fa-comments text-muted mb-3" style="font-size: 3rem;"></i>
                                        <h4 class="text-muted mb-3">No Chat Items Found</h4>
                                        <p class="text-muted mb-4">You haven't started any conversations yet.</p>
                                        <a href="/browse" class="btn btn-primary">Browse All Items</a>
                                    {% elseif selectedCategory != 'all' %}
                                        <i class="fas fa-search text-muted mb-3" style="font-size: 3rem;"></i>
                                        <h4 class="text-muted mb-3">No Items in This Category</h4>
                                        <p class="text-muted mb-4">No items found in the "{{ selectedCategory }}" category.</p>
                                        <a href="/browse?category=all" class="btn btn-primary">View All Categories</a>
                                    {% else %}
                                        <i class="fas fa-box-open text-muted mb-3" style="font-size: 3rem;"></i>
                                        <h4 class="text-muted mb-3">No Items Found</h4>
                                        <p class="text-muted mb-4">No items match your current filters.</p>
                                        <a href="/browse" class="btn btn-primary">Reset Filters</a>
                                    {% endif %}
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </section>
</main>

<!-- Item Calendar Modal -->
<div class="modal fade" id="calendarModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Item Calendar</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="calendarContent">
                    <p class="text-center">Loading calendar...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Chat Modal -->
<div class="modal fade" id="chatModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Chat with Owner</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="chatMessages" style="height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                    <p class="text-center text-muted">Loading chat history...</p>
                </div>
                <div class="input-group">
                    <input type="text" id="chatInput" class="form-control" placeholder="Type your message...">
                    <button class="btn btn-primary" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentChatOwnerId = null;
let currentChatItemId = null;

function viewItemCalendar(itemId, itemTitle) {
    document.querySelector('#calendarModal .modal-title').textContent = `Calendar for ${itemTitle}`;
    
    // Show calendar content - for now showing a simple message
    // In a real implementation, this would fetch actual reservation data
    document.getElementById('calendarContent').innerHTML = `
        <div class="text-center">
            <h6>Reservation Calendar for "${itemTitle}"</h6>
            <p class="text-muted">No reservations currently scheduled.</p>
            <p class="small">Calendar integration would show available dates and existing bookings here.</p>
        </div>
    `;
    
    new bootstrap.Modal(document.getElementById('calendarModal')).show();
}

function chatWithOwner(ownerId, ownerName, itemId) {
    currentChatOwnerId = ownerId;
    currentChatItemId = itemId;
    
    document.querySelector('#chatModal .modal-title').textContent = `Chat with ${ownerName}`;
    
    // Load existing chat messages - for now showing placeholder
    document.getElementById('chatMessages').innerHTML = `
        <div class="text-center text-muted">
            <p>Start a conversation with ${ownerName} about this item.</p>
            <p class="small">Chat history would appear here in a real implementation.</p>
        </div>
    `;
    
    new bootstrap.Modal(document.getElementById('chatModal')).show();
}

function sendMessage() {
    const input = document.getElementById('chatInput');
    const message = input.value.trim();
    
    if (message && currentChatOwnerId) {
        // In a real implementation, this would send the message to the backend
        const messagesDiv = document.getElementById('chatMessages');
        messagesDiv.innerHTML += `
            <div class="mb-2">
                <strong>You:</strong> ${message}
                <small class="text-muted d-block">Just now</small>
            </div>
        `;
        
        input.value = '';
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
        
        // Simulate owner response after 2 seconds
        setTimeout(() => {
            messagesDiv.innerHTML += `
                <div class="mb-2">
                    <strong>Owner:</strong> Thanks for your interest! I'll get back to you soon.
                    <small class="text-muted d-block">Just now</small>
                </div>
            `;
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }, 2000);
    }
}

// Toggle favorite function
function toggleFavorite(itemId, button, heartIcon) {
    const userId = {{ currentUser ? currentUser.id : 'null' }};
    
    fetch(`/api/favorites/${itemId}?userId=${userId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.favorited) {
                heartIcon.style.color = '#dc3545'; // Red when favorited
                button.setAttribute('title', 'Remove from favorites');
            } else {
                heartIcon.style.color = '#ccc'; // Gray when not favorited
                button.setAttribute('title', 'Add to favorites');
            }
        }
    })
    .catch(error => {
        console.error('Error toggling favorite:', error);
    });
}

// Dedicated function for handling favorite button clicks
function handleFavoriteClick(event, itemId) {
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
    
    const button = event.currentTarget;
    const heartIcon = button.querySelector('i');
    
    // Toggle favorite status
    toggleFavorite(itemId, button, heartIcon);
    
    return false;
}

// Sort current items on page without navigation
function sortCurrentItems(sortType) {
    const itemsContainer = document.querySelector('.row.g-3');
    const itemCards = Array.from(itemsContainer.querySelectorAll('.col-12, .col-sm-6'));
    
    if (sortType === 'alphabetic') {
        itemCards.sort((a, b) => {
            const titleA = a.querySelector('.fw-medium')?.textContent?.trim() || '';
            const titleB = b.querySelector('.fw-medium')?.textContent?.trim() || '';
            return titleA.localeCompare(titleB);
        });
    } else if (sortType === 'newest') {
        itemCards.sort((a, b) => {
            // Get item IDs from the card elements (higher ID = newer)
            const idA = parseInt(a.querySelector('[data-item-id]')?.getAttribute('data-item-id') || '0');
            const idB = parseInt(b.querySelector('[data-item-id]')?.getAttribute('data-item-id') || '0');
            return idB - idA; // Sort descending (newest first)
        });
    } else if (sortType === 'random') {
        for (let i = itemCards.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [itemCards[i], itemCards[j]] = [itemCards[j], itemCards[i]];
        }
    }
    
    // Clear container and re-append sorted items
    itemsContainer.innerHTML = '';
    itemCards.forEach(card => itemsContainer.appendChild(card));
    
    // Update button states
    document.querySelectorAll('.btn').forEach(btn => {
        btn.classList.remove('btn-primary', 'btn-dark', 'btn-success');
        if (btn.textContent.includes('ALPHABETIC')) {
            btn.classList.add(sortType === 'alphabetic' ? 'btn-primary' : 'btn-outline-primary');
        } else if (btn.textContent.includes('NEWEST')) {
            btn.classList.add(sortType === 'newest' ? 'btn-success' : 'btn-outline-success');
        } else if (btn.textContent.includes('RANDOM')) {
            btn.classList.add(sortType === 'random' ? 'btn-dark' : 'btn-outline-secondary');
        }
    });
}

// Card navigation function
function navigateToItem(itemId, event) {
    // Don't navigate if clicking on buttons or links
    if (event.target.closest('a, button')) {
        return;
    }
    window.location.href = '/item/' + itemId;
}

// Open contact helper modal for hour offerings
function openContactHelperModal(userId, offeringId, helperName, serviceTitle) {
    // Populate modal with helper details
    document.getElementById('contactHelperModalLabel').textContent = 'Contact Helper';
    document.getElementById('helperName').textContent = helperName;
    document.getElementById('serviceTitle').textContent = serviceTitle;
    document.getElementById('contactForm').reset();
    
    // Store data for form submission
    document.getElementById('contactForm').dataset.userId = userId;
    document.getElementById('contactForm').dataset.offeringId = offeringId;
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('contactHelperModal'));
    modal.show();
}



// Handle Enter key in chat input - wait for DOM
document.addEventListener('DOMContentLoaded', function() {
    const chatInput = document.getElementById('chatInput');
    if (chatInput) {
        chatInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }
    
    // Update favorite button states based on user favorites
    updateFavoriteButtons();
    
    // Check if we're on My Favorites filter and handle accordingly
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('filter') === 'my-favorites' && {{ currentUser ? 'true' : 'false' }}) {
        filterByFavorites();
    }
});

// Update favorite button states
function updateFavoriteButtons() {
    const userId = {{ currentUser ? currentUser.id : 'null' }};
    
    fetch(`/api/favorites/user/${userId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success && data.favorites) {
            data.favorites.forEach(favorite => {
                const button = document.querySelector(`[data-item-id="${favorite.id}"]`);
                if (button) {
                    const heartIcon = button.querySelector('i');
                    heartIcon.style.color = '#dc3545';
                    button.setAttribute('title', 'Remove from favorites');
                }
            });
        }
    })
    .catch(error => {
        console.error('Error loading favorites:', error);
    });
}

// Filter by favorites function
function filterByFavorites() {
    const userId = {{ currentUser ? currentUser.id : 'null' }};
    
    fetch(`/api/favorites/user/${userId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (!data.favorites || data.favorites.length === 0) {
                // Show no favorites message
                const itemsContainer = document.querySelector('.row.g-3');
                itemsContainer.innerHTML = `
                    <div class="col-12 text-center" style="margin-top: 10px;">
                        <div class="medium text-center text-muted">
                            You have no Favorites to display right now.<br>
                            Click the heart <i class="fas fa-heart text-danger"></i> in the lower right of<br>
                            <a href="/browse?sort=random&category=all&filter=all" class="text-decoration-none text-primary">Lendable Listings</a> to return to them later!
                        </div>
                    </div>
                `;
                return;
            }
            
            // Get favorite item IDs from the returned item data
            const favoriteItemIds = data.favorites.map(fav => fav.item_id);
            
            // Hide all items that are not favorites
            const allItems = document.querySelectorAll('[data-item-id]');
            let visibleCount = 0;
            
            allItems.forEach(item => {
                const itemId = parseInt(item.dataset.itemId);
                const itemCard = item.closest('.col-md-6, .col-lg-4, .col-12');
                
                if (favoriteItemIds.includes(itemId)) {
                    if (itemCard) {
                        itemCard.style.display = 'block';
                        visibleCount++;
                    }
                } else {
                    if (itemCard) itemCard.style.display = 'none';
                }
            });
            
            // Check if no favorites are actually visible on this page
            if (visibleCount === 0) {
                const itemsContainer = document.querySelector('.row.g-3');
                itemsContainer.innerHTML = `
                    <div class="col-12 text-center" style="margin-top: 10px;">
                        <div class="medium text-center text-muted">
                            You have no Favorites to display right now. Use the heart <i class="fas fa-heart text-danger"></i> in the lower right of 
                            <a href="/browse?sort=random&category=all&filter=all" class="text-decoration-none text-primary">Lendable Listings</a> 
                            to save Items to refer to later!
                        </div>
                    </div>
                `;
            }
            
            // Update visible count
            updateItemCount(visibleCount);
        } else {
            // Handle case where API call succeeds but no favorites property
            const itemsContainer = document.querySelector('.row.g-3');
            itemsContainer.innerHTML = `
                <div class="col-12 text-center" style="margin-top: 10px;">
                    <div class="medium text-center text-muted">
                        You have no Favorites to display right now.<br>
                        Click the heart <i class="fas fa-heart text-danger"></i> in the lower right of<br>
                        <a href="/browse?sort=random&category=all&filter=all" class="text-decoration-none text-primary">Lendable Listings</a> to return to them later!
                    </div>
                </div>
            `;
            updateItemCount(0);
        }
    })
    .catch(error => {
        console.error('Error loading favorites:', error);
        LocalLendables.showToast('Error', 'Error loading favorites. Please try again.', 'error');
    });
}

// Update item count display
function updateItemCount(count) {
    const countElement = document.getElementById('items-shown');
    if (countElement) {
        countElement.textContent = count;
    }
}

// Force reload all images function
function forceReloadAllImages() {
    const timestamp = new Date().getTime();
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        const src = img.src;
        // Remove existing cache-busting parameter if present
        const cleanSrc = src.split('?')[0];
        // Add new timestamp parameter
        img.src = cleanSrc + '?v=' + timestamp;
    });
    
    // Show feedback to user
    const button = event.target.closest('button');
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-check"></i> Reloaded!';
    button.classList.remove('btn-outline-warning');
    button.classList.add('btn-success');
    
    setTimeout(() => {
        button.innerHTML = originalText;
        button.classList.remove('btn-success');
        button.classList.add('btn-outline-warning');
    }, 2000);
}

// Send contact message for hour offerings
function sendContactMessage() {
    const form = document.getElementById('contactForm');
    const userId = form.dataset.userId;
    const offeringId = form.dataset.offeringId;
    const message = document.getElementById('contactMessage').value.trim();
    
    if (!message) {
        alert('Please enter a message before sending.');
        return;
    }
    
    // For now, redirect to browse-hours with message parameter
    // TODO: Implement direct messaging API
    const encodedMessage = encodeURIComponent(message);
    window.location.href = `/browse-hours?user=${userId}&offering=${offeringId}&message=${encodedMessage}`;
}
</script>

<!-- Contact Helper Modal -->
<div class="modal fade" id="contactHelperModal" tabindex="-1" aria-labelledby="contactHelperModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="contactHelperModalLabel">Contact Helper</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <h6>Helper</h6>
                    <p id="helperName" class="mb-1 fw-bold"></p>
                </div>
                <div class="mb-3">
                    <h6>Service</h6>
                    <p id="serviceTitle" class="mb-1 text-info"></p>
                </div>
                <form id="contactForm">
                    <div class="mb-3">
                        <label for="contactMessage" class="form-label">Your Message</label>
                        <textarea class="form-control" id="contactMessage" rows="4" 
                                  placeholder="Hi! I'm interested in your hour offering. Could you help me with..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="sendContactMessage()">
                    <i class="fas fa-paper-plane me-1"></i>Send Message
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.browse-action-btn {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.browse-action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    background-color: rgba(13, 110, 253, 0.1);
}

.browse-action-btn.btn-outline-success:hover {
    background-color: rgba(25, 135, 84, 0.1);
}

.browse-action-btn img {
    transition: transform 0.3s ease;
}

.browse-action-btn:hover img {
    transform: scale(1.1);
}

.hover-effect-target {
    transition: all 0.3s ease;
    background: transparent !important;
}

.hover-effect-target:hover {
    transform: scale(1.05);
    filter: brightness(1.1);
}

/* Ensure table cells don't add backgrounds to images */
td img {
    background: transparent !important;
}

/* Admin Edit Badge Styling */
.admin-edit-badge {
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
    border: 1px solid #ffc107 !important;
}

.admin-edit-badge:hover {
    background-color: #ffc107 !important;
    color: #000 !important;
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(255, 193, 7, 0.3);
    text-decoration: none !important;
}

.admin-edit-badge:active {
    transform: translateY(0);
    box-shadow: 0 1px 3px rgba(255, 193, 7, 0.3);
}
</style>

{% endblock %}