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

{% block title %}{{ item.title }} - Local Lendables{% endblock %}

{% block head %}
<style>
/* Circular Action Buttons */
.circular-action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 10px;
    border-radius: 15px;
    min-width: 120px;
}

.circular-action-btn:hover:not(.disabled) {
    background-color: rgba(0, 123, 255, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.circular-btn-img {
    width: 120px;
    height: auto;
    object-fit: contain;
    margin-bottom: 8px;
    transition: transform 0.3s ease;
}

.circular-action-btn:hover:not(.disabled) .circular-btn-img {
    transform: scale(1.1);
}

.circular-btn-text {
    font-size: 14px;
    font-weight: 600;
    text-align: center;
    color: #333;
    line-height: 1.2;
}

.circular-action-btn.disabled {
    cursor: not-allowed;
    opacity: 0.6;
}

.circular-action-btn.disabled .circular-btn-text {
    color: #6c757d;
}

.grayscale {
    filter: grayscale(100%);
}

.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
    max-width: 400px;
    margin: 0 auto;
}

.calendar-day {
    aspect-ratio: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.calendar-day:hover {
    transform: scale(1.05);
}

.calendar-day-header {
    font-weight: bold;
    background-color: #f8f9fa;
    border: none;
    cursor: default;
}

.calendar-day-header:hover {
    transform: none;
}

.day-available {
    background-color: #d4edda;
    color: #155724;
    border-color: #c3e6cb;
}

.day-reserved {
    background-color: #fff3cd;
    color: #856404;
    border-color: #ffeaa7;
}

.day-on-loan {
    background-color: #f8d7da;
    color: #721c24;
    border-color: #f5c6cb;
}

.day-today {
    border: 2px solid #007bff;
    font-weight: bold;
}

/* 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);
}

/* Circular Action Button Hover Effects */
.circular-action-btn {
    transition: all 0.3s ease;
    cursor: pointer;
    display: inline-block;
}

.circular-action-btn:hover .circular-btn-img {
    transform: scale(1.1);
    filter: brightness(1.1);
}

.circular-action-btn.disabled {
    cursor: not-allowed;
    opacity: 0.6;
}

.circular-action-btn.disabled:hover .circular-btn-img {
    transform: none;
    filter: none;
}

.circular-btn-img {
    transition: all 0.3s ease;
}

/* Chat panel styles */
.chat-panel {
    max-height: 500px;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    background: white;
}

.chat-messages {
    height: 300px;
    overflow-y: auto;
    padding: 1rem;
    border-bottom: 1px solid #dee2e6;
}

.message {
    margin-bottom: 1rem;
    padding: 0.5rem;
    border-radius: 0.375rem;
}

.message.sent {
    background-color: #007bff;
    color: white;
    margin-left: 20%;
    text-align: right;
}

.message.received {
    background-color: #f8f9fa;
    color: #333;
    margin-right: 20%;
}

.message-content {
    word-wrap: break-word;
}

.timestamp {
    opacity: 0.7;
    font-size: 0.75rem;
}

.audio-message {
    margin: 0.5rem 0;
}

.transcription {
    font-style: italic;
    margin-top: 0.5rem;
    font-size: 0.9rem;
}

.recording-controls {
    padding: 1rem;
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

.recording-status {
    color: #dc3545;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.recording-time {
    font-family: monospace;
    font-size: 1.1rem;
}

.audio-preview {
    padding: 1rem;
    background-color: #e3f2fd;
    border-bottom: 1px solid #dee2e6;
}

.message-input-area {
    padding: 1rem;
}

.btn-group-toggle {
    margin-bottom: 0.5rem;
}

/* Panel styles */
.panel {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    margin-bottom: 1rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.panel-header {
    background-color: #f8f9fa;
    padding: 1rem;
    border-bottom: 1px solid #dee2e6;
    font-weight: 600;
}

.panel-body {
    padding: 1.5rem;
}

/* JAVASCRIPT-CONTROLLED LAYOUT SYSTEM - v9 */

/* Both layouts hidden by default, JavaScript will show the correct one */
.mobile-header-layout {
    display: none;
    align-items: flex-start;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.desktop-header-layout {
    display: none;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 1.5rem;
}

.mobile-item-image {
    width: 80px !important;
    max-width: 80px !important;
    min-width: 80px !important;
    height: auto !important;
    object-fit: contain !important;
    flex-shrink: 0;
    cursor: pointer;
    transition: transform 0.2s ease;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

/* Force mobile image size on mobile layouts - extra specific */
.mobile-header-layout .mobile-item-image {
    width: 80px !important;
    max-width: 80px !important;
    min-width: 80px !important;
}

/* Override any Bootstrap img classes */
.mobile-header-layout img.mobile-item-image {
    width: 80px !important;
    max-width: 80px !important;
}
</style>
{% endblock %}

{% block content %}

<!-- Main Content -->
<main class="container-fluid py-4" style="background-color: #f8f9fa;">
    <div class="container">
        <div class="row">
            <!-- Main Content Area -->
            <div class="col">
                <div class="row">
                    <!-- Item Details Section -->
                    <div class="{% if item.isRequest %}col-lg-12{% else %}col-lg-8{% endif %}">
                        <div class="mb-3">
                            <!-- Mobile Header Layout: Item image + content -->
                            <div class="mobile-header-layout">
                                {% if not item.isRequest and item.primaryLogo and item.primaryLogo != 'default-placeholder.jpg' %}
                                    <img src="/lendable_items/{{ item.primaryLogo }}" alt="{{ item.name }}" 
                                         class="mobile-item-image"
                                         style="width: 80px !important; max-width: 80px !important; height: auto !important; object-fit: contain !important;"
                                         onclick="openImageModal('/lendable_items/{{ item.primaryLogo }}', '{{ item.name }}')"
                                         title="Click to view full size">
                                {% elseif item.isRequest %}
                                    <a name="asking-for-section" id="asking-for-section"></a>
                                    <img src="/lendables/logo_askfor_600.png" alt="Ask Request" 
                                         class="mobile-item-image">
                                {% else %}
                                    <img src="/lendables/logo_item_listing_600.png" alt="Item Listing" 
                                         class="mobile-item-image">
                                {% endif %}
                                
                                <div class="flex-grow-1">
                                    {% if item.isRequest %}
                                        <div class="mb-2">
                                            <div class="display-6 fw-bold text-muted">Asking For:</div>
                                        </div>
                                    {% endif %}
                                    <h1 class="display-6 fw-bold mb-1" id="item-title" style="line-height: 1.0;">{{ item.name }}{% if item.isRequest %}?{% endif %}</h1>
                                    
                                    <div class="mb-1 d-flex align-items-center justify-content-between">
                                        <div>
                                            <a href="/browse?category={{ item.category }}" class="text-decoration-none">
                                                <span class="badge bg-primary me-2" style="cursor: pointer;" title="View all items in {{ item.categoryName ?: 'Uncategorized' }} category">{{ item.categoryName ?: 'Uncategorized' }}</span>
                                            </a>
                                            {% if item.isRequest %}
                                                <span class="badge bg-info me-2">Request</span>
                                                {% if item.urgency %}
                                                    {% if item.urgency == 'urgent' %}
                                                        <span class="badge bg-danger me-2">Urgent</span>
                                                    {% elseif item.urgency == 'high' %}
                                                        <span class="badge bg-warning me-2">High Priority</span>
                                                    {% endif %}
                                                {% endif %}
                                            {% elseif item.pricePerDay and item.pricePerDay > 0 %}
                                                <span class="badge bg-danger me-2 badge-nowrap">Rentable</span>
                                            {% else %}
                                                <span class="badge bg-success me-2 badge-nowrap">Lendable</span>
                                            {% endif %}
                                        </div>
                                        <!-- Favorites Heart Button -->
                                        <button class="btn btn-link p-0 border-0 favorite-btn" 
                                                data-item-id="{{ item.id }}" 
                                                data-user-id="{{ currentUser.id }}"
                                                title="{% if isFavorited %}Remove from favorites{% else %}Add to favorites{% endif %}"
                                                style="background: none; line-height: 1; pointer-events: auto; z-index: 1000; position: relative;"
                                                onclick="toggleFavorite({{ item.id }}, this, this.querySelector('i'))">
                                            <i class="fas fa-heart" style="color: {% if isFavorited %}#dc3545{% else %}#ccc{% endif %}; font-size: 1.5rem; transition: color 0.3s;"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Desktop Header Layout: Original design -->
                            <div class="desktop-header-layout">
                                <div class="d-flex align-items-start">
                                    <div class="item-listing-logo me-4">
                                        {% if item.isRequest %}
                                            <a name="asking-for-section" id="asking-for-section"></a>
                                            <img src="/lendables/logo_askfor_600.png" alt="Ask Request" 
                                                 style="width: 120px; height: auto; object-fit: contain;">
                                        {% else %}
                                            <img src="/lendables/logo_item_listing_600.png" alt="Item Listing" 
                                                 style="width: 120px; height: auto; object-fit: contain;">
                                        {% endif %}
                                    </div>
                                    <div class="flex-grow-1">
                                        {% if item.isRequest %}
                                            <div class="mb-2">
                                                <div class="display-6 fw-bold text-muted">Asking For:</div>
                                            </div>
                                        {% endif %}
                                        <h1 class="display-6 fw-bold mb-1" id="item-title" style="line-height: 1.0;">{{ item.name }}{% if item.isRequest %}?{% endif %}</h1>
                                    
                                    <div class="mb-1 d-flex align-items-center justify-content-between">
                                        <div>
                                            <a href="/browse?category={{ item.category }}" class="text-decoration-none">
                                                <span class="badge bg-primary me-2" style="cursor: pointer;" title="View all items in {{ item.categoryName ?: 'Uncategorized' }} category">{{ item.categoryName ?: 'Uncategorized' }}</span>
                                            </a>
                                            {% if item.isRequest %}
                                                <span class="badge bg-info me-2">Request</span>
                                                {% if item.urgency %}
                                                    {% if item.urgency == 'urgent' %}
                                                        <span class="badge bg-danger me-2">Urgent</span>
                                                    {% elseif item.urgency == 'high' %}
                                                        <span class="badge bg-warning me-2">High Priority</span>
                                                    {% endif %}
                                                {% endif %}
                                            {% elseif item.pricePerDay and item.pricePerDay > 0 %}
                                                <span class="badge bg-danger me-2 badge-nowrap">Rentable</span>
                                            {% else %}
                                                <span class="badge bg-success me-2 badge-nowrap">Lendable</span>
                                            {% endif %}
                                        </div>
                                        <!-- Favorites Heart Button -->
                                        <button class="btn btn-link p-0 border-0 favorite-btn" 
                                                data-item-id="{{ item.id }}" 
                                                data-user-id="{{ currentUser.id }}"
                                                title="{% if isFavorited %}Remove from favorites{% else %}Add to favorites{% endif %}"
                                                style="background: none; line-height: 1; pointer-events: auto; z-index: 1000; position: relative;"
                                                onclick="toggleFavorite({{ item.id }}, this, this.querySelector('i'))">
                                            <i class="fas fa-heart" style="color: {% if isFavorited %}#dc3545{% else %}#ccc{% endif %}; font-size: 1.5rem; transition: color 0.3s;"></i>
                                        </button>
                                    </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Owner Information Section -->
                            <div class="d-flex align-items-center justify-content-between mb-3">
                                <div class="d-flex align-items-center">
                                    <strong class="me-2 p-1">{% if item.isRequest %}Requested By{% else %}Offered By{% endif %}</strong>
                                    <img src="/ll_images/{{ item.ownerAvatar }}" 
                                         alt="{{ item.ownerFirstName }}" 
                                         class="rounded-circle me-2"
                                         style="width: 32px; height: 32px; object-fit: cover;"
                                         onerror="this.src='/avatars/default.svg'">
                                    <span class="text-success fw-bold">{{ item.ownerShowName ?: item.ownerFirstName }}</span>
                                </div>
                                {% if session.userId == item.owner %}
                                    <a href="/edit-item/{{ item.id }}" class="btn btn-outline-success btn-sm">
                                        <i class="fas fa-edit me-1"></i>Edit
                                    </a>
                                {% endif %}
                            </div>
                            <div class="mb-3">
                                <small class="text-muted p-1">Added On - {{ item.addedOn|date('M j Y') }}</small>
                            </div>



                            <!-- Item Description -->
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="card-title">Description</h5>
                                    <p class="card-text">{{ item.description }}</p>
                                    
                                    {% if item.specialInstructions %}
                                    <div class="mt-2">
                                        <p class="card-text" style="font-family: Helvetica, Arial, sans-serif; font-size: 0.9rem; color: #6c757d; margin-bottom: 0;">{{ item.specialInstructions }}</p>
                                    </div>
                                    {% endif %}
                                    
                                    {% if not item.isRequest %}
                                    <div class="row g-3 mt-3">
                                        <div class="col-sm-6">
                                            <strong class="p-1">Condition:</strong> 
                                            {% if item.condition %}
                                                {{ item.condition|title }}
                                            {% else %}
                                                <span class="text-muted">Not specified</span>
                                            {% endif %}
                                        </div>
                                        <div class="col-sm-6">
                                            <strong>Availability:</strong> 
                                            {% if loanStatus and loanStatus.isOnLoan %}
                                                <span class="badge bg-warning">Out on Loan</span>
                                            {% else %}
                                                <span class="badge bg-success">Available</span>
                                            {% endif %}
                                        </div>
                                        {% if item.pricePerDay and item.pricePerDay > 0 %}
                                        <div class="col-sm-6">
                                            <strong>Daily Rate:</strong> ${{ item.pricePerDay }}
                                        </div>
                                        {% if item.deposit %}
                                        <div class="col-sm-6">
                                            <strong>Deposit:</strong> ${{ item.deposit }}
                                        </div>
                                        {% endif %}
                                        {% endif %}
                                    </div>
                                    {% endif %}
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="mb-4">
                                {% if item.isRequest %}
                                    <!-- Show Create Lendable Item button for Ask requests if not owned by current user -->
                                    {% if session.userId != item.owner %}
                                        <div class="d-flex gap-3 justify-content-center mb-3">
                                            <div class="circular-action-btn tooltip-enhanced" onclick="window.location.href='/create-item'" title="Create a Lendable Item to help {{ item.ownerShowName ?: item.ownerFirstName }}">
                                                <img src="/lendables/logo_create_600.png" alt="Create Lendable Item" 
                                                     class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                            </div>
                                            <div class="circular-action-btn tooltip-enhanced" onclick="toggleChatPanel()" title="Chat with {{ item.ownerShowName ?: item.ownerFirstName }} about this request">
                                                <img src="/lendables/logo_chat2_600.png" alt="Chat about Request" 
                                                     class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                            </div>
                                        </div>
                                        
                                        <!-- Guidance text for Ask For items -->
                                        <div class="text-center">
                                            <p class="small text-muted mb-0">
                                                If you can create a Lendable "{{ item.name }}" that helps out {{ item.ownerShowName ?: item.ownerFirstName }}, use the button above -- or send {{ item.ownerShowName ?: item.ownerFirstName }} a Chat message below.
                                            </p>
                                        </div>
                                    {% endif %}
                                {% else %}
                                    <div class="d-flex gap-3 justify-content-center">
                                        <!-- Show Calendar button for all users (owners and non-owners) -->
                                        <div class="circular-action-btn tooltip-enhanced" onclick="openCalendarModal()" title="{% if session.userId == item.owner %}View item availability calendar{% else %}{% if loanStatus and loanStatus.isOnLoan %}View availability and reserve for future dates{% else %}{% if item.pricePerDay and item.pricePerDay > 0 %}View calendar and request to rent{% else %}View calendar and request to borrow{% endif %}{% endif %}{% endif %}">
                                            <img src="/lendables/logo_checkdates_600.png" alt="Calendar &amp; Availability" 
                                                 class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                        </div>
                                        
                                        <!-- Show Item Now Back button for owners when item is on loan -->
                                        {% if session.userId == item.owner and loanStatus and loanStatus.isOnLoan %}
                                            <div class="circular-action-btn tooltip-enhanced" onclick="openPushReturnModal()" title="Mark item as returned (Item Now Back?)">
                                                <img src="/lendables/logo_confirm_600.png" alt="Item Now Back?" 
                                                     class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                            </div>
                                        {% endif %}
                                        
                                        <!-- Show Chat button only when there's an existing conversation -->
                                        {% if existingConversation %}
                                            <div class="circular-action-btn tooltip-enhanced" onclick="toggleChatPanel()" title="{% if session.userId == item.owner %}Chat with {{ existingConversation.borrower_show_name ?: existingConversation.borrower_first_name }}{% else %}Chat with {{ item.ownerShowName ?: item.ownerFirstName }}{% endif %} about this item">
                                                <img src="/lendables/logo_chat2_600.png" alt="Chat about Item" 
                                                     class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                            </div>
                                        {% endif %}
                                        
                                        <!-- Show View Handshake Agreement button if there's a signed agreement -->
                                        {% if signedAgreement %}
                                            <div class="circular-action-btn tooltip-enhanced" onclick="window.open('/agreement/{{ signedAgreement.id }}', '_blank')" title="View Handshake Agreement">
                                                <img src="/lendables/logo_confirm_600.png" alt="View Handshake Agreement" 
                                                     class="circular-btn-img" style="width: 120px !important; height: auto !important;">
                                            </div>
                                        {% endif %}
                                    </div>
                                {% endif %}
                            </div>

                            <!-- Chat Panel (Hidden by default) -->
                            <div id="chatPanel" class="card mb-4" style="display: none;">
                                <a name="chat-section" id="chat-section"></a>
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <div>
                                        <h5 class="mb-0">Chat with {% if currentUser and item.owner == currentUser.id and existingConversation %}{{ existingConversation.borrower_show_name ?: existingConversation.borrower_first_name }}{% else %}{{ item.ownerShowName ?: item.ownerFirstName }}{% endif %}</h5>
                                        {% if not item.isRequest %}
                                            <p class="small text-dark mb-0">Use the "Check Dates" button above to start a scheduled Lendable. Use this Chat for other questions.</p>
                                        {% endif %}
                                    </div>
                                    <button type="button" class="btn-close" onclick="toggleChatPanel()" aria-label="Close"></button>
                                </div>
                                <div class="card-body">
                                    <!-- Contextual Help Banner for Borrowing -->
                                    <div id="borrowingHelpBanner" class="alert alert-info alert-dismissible fade show d-none" role="alert">
                                        <div class="d-flex align-items-start">
                                            <i class="fas fa-lightbulb me-2 mt-1"></i>
                                            <div class="flex-grow-1">
                                                <strong>Want to borrow this item?</strong><br>
                                                <small>For formal requests with specific dates, use the <strong>Calendar & Availability</strong> button above. Chat is perfect for questions and coordination!</small>
                                            </div>
                                        </div>
                                        <button type="button" class="btn-close" onclick="dismissBorrowingHelp()" aria-label="Close"></button>
                                    </div>

                                    <!-- Message Input at Top -->
                                    <label for="messageInput" class="form-label mb-2">Type your message</label>
                                    <div class="input-group mb-2">
                                        <input type="text" id="messageInput" class="form-control" placeholder="Type a Message to {% if currentUser and item.owner == currentUser.id and existingConversation %}{{ existingConversation.borrower_show_name ?: existingConversation.borrower_first_name }}{% else %}{{ item.ownerShowName ?: item.ownerFirstName }}{% endif %} here" onkeypress="handleMessageKeyPress(event)">
                                        <button class="btn btn-primary" type="button" onclick="sendTextMessage()">
                                            <i class="fas fa-paper-plane"></i>
                                        </button>
                                    </div>
                                    <div class="text-start mb-3">
                                        <small class="text-muted">or</small>
                                    </div>
                                    
                                    <!-- Audio Recording Controls at Top -->
                                    <div class="audio-controls mb-3">
                                        <div class="btn-group mb-2" role="group">
                                            <button id="recordBtn" class="btn btn-outline-danger btn-sm" onclick="startRecording()">
                                                <i class="fas fa-microphone"></i> Record Voicemail for {% if currentUser and item.owner == currentUser.id and existingConversation %}{{ existingConversation.borrower_show_name ?: existingConversation.borrower_first_name }}{% else %}{{ item.ownerShowName ?: item.ownerFirstName }}{% endif %}
                                            </button>
                                            <button id="stopBtn" class="btn btn-outline-success btn-sm" onclick="stopRecording()" style="display: none;">
                                                <i class="fas fa-stop"></i> Stop Recording
                                            </button>
                                        </div>
                                        
                                        <div id="recordingStatus" class="text-muted small mb-2" style="display: none;">
                                            <i class="fas fa-circle text-danger blink"></i> Recording... <span id="recordingTime">0:00</span>
                                        </div>
                                        
                                        <div id="audioPreview" class="audio-preview" style="display: none;">
                                            <div class="d-flex align-items-center gap-2 p-2 bg-light rounded">
                                                <audio id="audioPlayback" controls class="flex-grow-1"></audio>
                                                <div class="btn-group-vertical">
                                                    <button id="sendAudioBtn" class="btn btn-success btn-sm" onclick="sendAudioMessage()">
                                                        <i class="fas fa-paper-plane"></i> Send Audio
                                                    </button>
                                                    <button id="cancelAudioBtn" class="btn btn-secondary btn-sm" onclick="cancelAudioMessage()">
                                                        <i class="fas fa-times"></i> Cancel
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Divider -->
                                    <hr class="my-3">
                                    
                                    <!-- Messages Display -->
                                    <div id="chatMessages" class="mb-3">
                                        <div class="text-center text-muted p-3">
                                            <i class="fas fa-spinner fa-spin"></i> Loading messages...
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Borrow Panel (Hidden by default) -->
                            <div id="borrowPanel" class="card mb-4" style="display: none;">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">{% if item.pricePerDay and item.pricePerDay > 0 %}Request to Rent{% else %}Request to Borrow{% endif %}</h5>
                                    <button type="button" class="btn-close" onclick="toggleBorrowPanel()" aria-label="Close"></button>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <button onclick="changeBorrowMonth(-1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                        <h6 id="borrowCurrentMonth" class="mb-0">{{ "now"|date("F Y") }}</h6>
                                        <button onclick="changeBorrowMonth(1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead>
                                                <tr class="text-center">
                                                    <th style="width: 14.28%;">Sun</th>
                                                    <th style="width: 14.28%;">Mon</th>
                                                    <th style="width: 14.28%;">Tue</th>
                                                    <th style="width: 14.28%;">Wed</th>
                                                    <th style="width: 14.28%;">Thu</th>
                                                    <th style="width: 14.28%;">Fri</th>
                                                    <th style="width: 14.28%;">Sat</th>
                                                </tr>
                                            </thead>
                                            <tbody id="borrowCalendarGrid">
                                                <!-- Calendar days will be populated by JavaScript -->
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <div class="d-flex flex-wrap gap-2 mb-2">
                                            <span class="badge bg-success">Available</span>
                                            <span class="badge bg-warning text-dark">Reserved</span>
                                            <span class="badge bg-danger">On Loan</span>
                                            <span class="badge" style="background-color: #8B0000; color: white;">Overdue</span>
                                            <span class="badge" style="background-color: #0d6efd; color: white;">Selected</span>
                                        </div>
                                        <div class="small text-muted mb-3">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Click start date, then end date to select a range
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <button onclick="clearSelectedDates()" class="btn btn-outline-secondary btn-sm">Clear Selection</button>
                                            <button onclick="sendBorrowRequest()" class="btn btn-success btn-sm" id="sendBorrowRequestBtn" disabled>Create Request</button>
                                        </div>
                                    </div>
                                    
                                    <div id="borrowSelectedDates" class="mt-2" style="display: none;">
                                        <small class="text-muted">Selected dates: <span id="borrowSelectedDatesList"></span></small>
                                    </div>
                                </div>
                            </div>

                            <!-- Calendar Panel (Hidden by default) -->
                            <div id="calendarPanel" class="card mb-4" style="display: none;">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">{{ item.name }}<br>Calendar & Availability</h5>
                                    <button type="button" class="btn-close" onclick="toggleCalendarPanel()" aria-label="Close"></button>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <button onclick="changeCalendarMonth(-1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                        <h6 id="calendarCurrentMonth" class="mb-0">{{ "now"|date("F Y") }}</h6>
                                        <button onclick="changeCalendarMonth(1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead>
                                                <tr class="text-center">
                                                    <th style="width: 14.28%;">Sun</th>
                                                    <th style="width: 14.28%;">Mon</th>
                                                    <th style="width: 14.28%;">Tue</th>
                                                    <th style="width: 14.28%;">Wed</th>
                                                    <th style="width: 14.28%;">Thu</th>
                                                    <th style="width: 14.28%;">Fri</th>
                                                    <th style="width: 14.28%;">Sat</th>
                                                </tr>
                                            </thead>
                                            <tbody id="viewCalendarGrid">
                                                <!-- Calendar days will be populated by JavaScript -->
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <div>
                                            <span class="badge bg-success me-2">Available</span>
                                            <span class="badge bg-warning me-2">Reserved</span>
                                            <span class="badge bg-danger me-2">On Loan</span>
                                            <span class="badge me-2" style="background-color: #8B0000; color: white;">Overdue</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Admin/Owner Edit Controls -->
                            {% if canEdit %}
                            <div class="text-center mb-4">
                                <div class="d-inline-flex gap-2">
                                    {% if currentUser and item.owner == currentUser.id %}
                                        <a href="/edit-item/{{ item.id }}" class="btn btn-outline-success">
                                            <i class="fas fa-edit me-1"></i>Edit Item
                                        </a>
                                        <a href="/print-labels/{{ item.id }}" target="_blank" class="btn btn-primary">
                                            <i class="fas fa-print me-1"></i>Print Labels
                                        </a>
                                    {% elseif isAdmin and item.owner != currentUser.id %}
                                        <a href="/edit-item/{{ item.id }}" class="badge bg-warning text-dark text-decoration-none align-self-center admin-edit-badge" title="Click to edit as Admin">
                                            <i class="fas fa-edit me-1"></i>ADMIN
                                        </a>
                                    {% endif %}
                                    <button class="btn btn-outline-danger" onclick="deleteItem({{ item.id }})">
                                        <i class="fas fa-trash me-1"></i>Delete Item
                                    </button>
                                </div>
                            </div>
                            {% endif %}

                            <!-- Calendar Section (Hidden by default) -->
                            <div id="calendarSection" class="card" style="display: none;">
                                <a name="borrow"></a>
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">Availability Calendar</h5>
                                    <small class="text-muted">Select dates to request borrowing</small>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <button onclick="changeBorrowMonth(-1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                        <h6 id="borrowCurrentMonth" class="mb-0">{{ "now"|date("F Y") }}</h6>
                                        <button onclick="changeBorrowMonth(1)" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive" style="min-height: 300px; overflow: visible;">
                                        <table class="table table-sm table-bordered" style="width: 100%; table-layout: fixed;"
                                            <thead>
                                                <tr class="text-center">
                                                    <th style="width: 14.28%;">Sun</th>
                                                    <th style="width: 14.28%;">Mon</th>
                                                    <th style="width: 14.28%;">Tue</th>
                                                    <th style="width: 14.28%;">Wed</th>
                                                    <th style="width: 14.28%;">Thu</th>
                                                    <th style="width: 14.28%;">Fri</th>
                                                    <th style="width: 14.28%;">Sat</th>
                                                </tr>
                                            </thead>
                                            <tbody id="borrowCalendarGrid">
                                                <!-- Calendar days will be populated by JavaScript -->
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <div class="mt-3 d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="badge bg-success me-2">Available</span>
                                            <span class="badge bg-warning me-2">Reserved</span>
                                            <span class="badge bg-danger me-2">On Loan</span>
                                            <span class="badge bg-primary me-2">Selected</span>
                                        </div>
                                        <div>
                                            <button onclick="clearSelectedDates()" class="btn btn-outline-secondary btn-sm me-2">Clear Selection</button>
                                            <button onclick="sendBorrowRequest()" class="btn btn-success btn-sm" id="sendBorrowRequestBtn" disabled>Create Request</button>
                                        </div>
                                    </div>
                                    
                                    <div id="borrowSelectedDates" class="mt-2" style="display: none;">
                                        <small class="text-muted">Selected dates: <span id="borrowSelectedDatesList"></span></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Image Section (only for regular items, not requests) -->
                    {% if not item.isRequest %}
                    <div class="col-lg-4">
                        <div class="sticky-top" style="top: 20px;">
                            {% if item.primaryLogo or item.imageUrl %}
                                <div class="card">
                                    <div class="card-body p-0">
                                        <img src="/lendable_items/{{ item.primaryLogo ? item.primaryLogo : item.imageUrl }}" 
                                             alt="{{ item.title }}" 
                                             class="img-fluid w-100 rounded"
                                             style="max-height: 400px; object-fit: cover; cursor: pointer;"
                                             onclick="openImageModal('{{ item.primaryLogo ? item.primaryLogo : item.imageUrl }}', '{{ item.title }}')"
                                             onerror="this.src='/lendable_items/default-placeholder.jpg'">
                                    </div>
                                    
                                </div>
                                
                                <!-- Additional Images (Full Display) -->
                                {% if item.extraImages %}
                                    {% set extraImagesArray = item.extraImages|split(',') %}
                                    {% for extraImage in extraImagesArray %}
                                        {% if extraImage|trim %}
                                        <div class="card mt-3">
                                            <div class="card-body p-0">
                                                <img src="/lendable_items/{{ extraImage|trim }}" 
                                                     alt="{{ item.title }}" 
                                                     class="img-fluid w-100 rounded"
                                                     style="max-height: 400px; object-fit: cover; cursor: pointer;"
                                                     onclick="openImageModal('{{ extraImage|trim }}', '{{ item.title }}')">
                                            </div>
                                        </div>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                                </div>
                            {% else %}
                                <div class="bg-light rounded d-flex align-items-center justify-content-center" 
                                     style="height: 300px;">
                                    <div class="text-center text-muted">
                                        <i class="fas fa-image mb-2" style="font-size: 3rem;"></i>
                                        <p>No image available</p>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</main>

<!-- Image Modal -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="imageModalLabel">{{ item.name }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center p-0">
        <img id="modalImage" src="" alt="" class="img-fluid w-100" style="max-height: 80vh; object-fit: contain;">
      </div>
    </div>
  </div>
</div>

<!-- Profile Info Modal -->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="profileModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="profileModalLabel">Owner Profile</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center">
        <img src="/ll_images/{{ item.ownerAvatar }}" 
             alt="{{ item.ownerFirstName }}" 
             class="rounded-circle mb-3"
             style="width: 80px; height: 80px; object-fit: cover;"
             onerror="this.src='/avatars/default.svg'">
        <h5 class="mb-2">{{ item.ownerShowName ? item.ownerShowName : (item.ownerFirstName ~ ' ' ~ item.ownerLastName) }}</h5>
        <p class="text-muted mb-3">Community Member</p>
        <p class="mb-3"><i class="fas fa-star text-warning me-1"></i>Rating: {{ item.ownerRating ? item.ownerRating : 'New Member' }}</p>
        {% if item.ownerLocation %}
        <p class="mb-3"><i class="fas fa-map-marker-alt text-primary me-1"></i>{{ item.ownerLocation }}</p>
        {% endif %}
      </div>
      <div class="modal-footer justify-content-center">
        <a href="/profile/{{ item.userId }}" class="btn btn-primary">View Full Profile</a>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Rental Cost Calculation Modal -->
<div class="modal fade" id="rentalCostModal" tabindex="-1" aria-labelledby="rentalCostModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="rentalCostModalLabel">
          <img src="/lendables/logo_checkdates_600.png" alt="Rental" class="me-2" style="width: 30px; height: auto;">
          Rental Cost Calculation
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card border-0 bg-light mb-3">
          <div class="card-body">
            <h6 class="card-title text-primary mb-3">
              <i class="fas fa-calculator me-2"></i>Rental Summary
            </h6>
            <div class="row mb-2">
              <div class="col-4"><strong>Item:</strong></div>
              <div class="col-8" id="rentalItemName"></div>
            </div>
            <div class="row mb-2">
              <div class="col-4"><strong>Start Date:</strong></div>
              <div class="col-8" id="rentalStartDate"></div>
            </div>
            <div class="row mb-2">
              <div class="col-4"><strong>End Date:</strong></div>
              <div class="col-8" id="rentalEndDate"></div>
            </div>
            <div class="row mb-2">
              <div class="col-4"><strong>Duration:</strong></div>
              <div class="col-8"><span id="rentalNumDays"></span> days</div>
            </div>
            <div class="row mb-2">
              <div class="col-4"><strong>Daily Rate:</strong></div>
              <div class="col-8" id="rentalDailyRate"></div>
            </div>
            <hr>
            <div class="row">
              <div class="col-4"><strong class="text-success">Total Cost:</strong></div>
              <div class="col-8"><strong class="text-success fs-5" id="rentalTotalCost"></strong></div>
            </div>
          </div>
        </div>
        
        <div class="mb-3">
          <label for="rentalMessage" class="form-label">Message to Owner (optional)</label>
          <textarea class="form-control" id="rentalMessage" rows="3" placeholder="Add any special notes or requests for this rental..."></textarea>
        </div>
        
        <div class="alert alert-info">
          <i class="fas fa-info-circle me-2"></i>
          <strong>Payment & Terms:</strong> Final payment arrangements and rental terms will be coordinated directly with the owner after your request is approved.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
          <i class="fas fa-times me-2"></i>Cancel
        </button>
        <button type="button" class="btn btn-success" onclick="handleRentalSubmission()">
          <i class="fas fa-paper-plane me-2"></i>Submit Rental Request
        </button>
      </div>
    </div>
  </div>
</div>

<!-- JavaScript for interactions -->
<script>
let currentDate = new Date();
let borrowCurrentDate = new Date();
let viewCurrentDate = new Date();
let calendarData = {};
let viewCalendarData = {};
let selectedDates = [];

// Range selection variables
let rangeStartDate = null;
let rangeEndDate = null;

// Chat functionality
let conversationId = {% if existingConversation %}{{ existingConversation.id }}{% else %}null{% endif %};
let mediaRecorder = null;
let recordingStartTime = null;
let recordingTimer = null;
let currentAudioBlob = null;
let isRecording = false;

function changeMainImage(imageName) {
    const mainImg = document.querySelector('img[src*="/lendable_items/"]');
    if (mainImg) {
        mainImg.src = '/lendable_items/' + imageName;
    }
}

function openImageModal(imageSrc, imageAlt) {
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    const modalImage = document.getElementById('modalImage');
    modalImage.src = '/lendable_items/' + imageSrc;
    modalImage.alt = imageAlt;
    modal.show();
}

function showProfileModal() {
    const modal = new bootstrap.Modal(document.getElementById('profileModal'));
    modal.show();
}

// Panel toggle functions
function toggleBorrowPanel() {
    const borrowPanel = document.getElementById('borrowPanel');
    if (!borrowPanel) {
        console.error('Borrow panel not found');
        return;
    }
    
    const isVisible = borrowPanel.style.display !== 'none';
    
    // Hide other panels (with safety checks)
    const chatPanel = document.getElementById('chatPanel');
    const calendarPanel = document.getElementById('calendarPanel');
    
    if (chatPanel) chatPanel.style.display = 'none';
    if (calendarPanel) calendarPanel.style.display = 'none';
    
    if (isVisible) {
        borrowPanel.style.display = 'none';
    } else {
        borrowPanel.style.display = 'block';
        borrowPanel.scrollIntoView({ behavior: 'smooth' });
        loadBorrowCalendar();
    }
}

function toggleChatPanel() {
    const chatPanel = document.getElementById('chatPanel');
    if (!chatPanel) {
        console.error('Chat panel not found');
        return;
    }
    
    const isVisible = chatPanel.style.display !== 'none';
    
    // Hide other panels (with safety checks)
    const borrowPanel = document.getElementById('borrowPanel');
    const calendarPanel = document.getElementById('calendarPanel');
    
    if (borrowPanel) borrowPanel.style.display = 'none';
    if (calendarPanel) calendarPanel.style.display = 'none';
    
    if (isVisible) {
        chatPanel.style.display = 'none';
    } else {
        chatPanel.style.display = 'block';
        chatPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
        initializeChat();
        
        // Show borrowing help banner for non-owners if not dismissed
        {% if currentUser and item.owner != currentUser.id %}
        if (!sessionStorage.getItem('borrowingHelpDismissed')) {
            setTimeout(() => {
                showBorrowingHelp();
            }, 1500); // Show after 1.5 seconds when chat opens
        }
        {% endif %}
    }
}

// Check if chat should be opened automatically when page loads
document.addEventListener('DOMContentLoaded', function() {
    if (sessionStorage.getItem('openChatOnLoad') === 'true') {
        sessionStorage.removeItem('openChatOnLoad');
        toggleChatPanel();
    }
});

function toggleCalendarPanel() {
    const calendarPanel = document.getElementById('calendarPanel');
    if (!calendarPanel) {
        console.error('Calendar panel not found');
        return;
    }
    
    const isVisible = calendarPanel.style.display !== 'none';
    
    // Hide other panels (with safety checks)
    const borrowPanel = document.getElementById('borrowPanel');
    const chatPanel = document.getElementById('chatPanel');
    
    if (borrowPanel) borrowPanel.style.display = 'none';
    if (chatPanel) chatPanel.style.display = 'none';
    
    if (isVisible) {
        calendarPanel.style.display = 'none';
    } else {
        calendarPanel.style.display = 'block';
        calendarPanel.scrollIntoView({ behavior: 'smooth' });
        loadViewCalendar();
    }
}

function showDateSelector() {
    toggleBorrowPanel();
}

function formatDateRange(dates) {
    if (dates.length === 0) return '';
    if (dates.length === 1) return dates[0];
    
    dates.sort();
    
    const groups = [];
    let currentGroup = [dates[0]];
    
    for (let i = 1; i < dates.length; i++) {
        const prevDate = new Date(dates[i-1]);
        const currDate = new Date(dates[i]);
        const timeDiff = currDate.getTime() - prevDate.getTime();
        const dayDiff = timeDiff / (1000 * 3600 * 24);
        
        if (dayDiff === 1) {
            currentGroup.push(dates[i]);
        } else {
            groups.push(currentGroup);
            currentGroup = [dates[i]];
        }
    }
    groups.push(currentGroup);
    
    return groups.map(group => {
        if (group.length === 1) {
            return group[0];
        } else if (group.length === 2) {
            return group[0] + ' and ' + group[1];
        } else {
            return group[0] + ' to ' + group[group.length - 1];
        }
    }).join(', ');
}

function sendBorrowRequest() {
    if (selectedDates.length === 0) {
        LocalLendables.showErrorToast('Selection Required', 'Please select at least one date for your request.');
        return;
    }
    
    const dateRange = formatDateRange(selectedDates);
    const isRentable = {{ item.pricePerDay and item.pricePerDay > 0 ? 'true' : 'false' }};
    const actionWord = isRentable ? 'rent' : 'borrow';
    const titleText = isRentable ? 'Ask to Rent' : 'Ask to Reserve';
    const defaultMessage = `Ok if I ${actionWord} {{ item.name }} on ${dateRange}? `;
    
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: titleText,
            html: `
                <div class="text-start">
                    <p><strong>Selected dates:</strong> ${dateRange}</p>
                    <label for="borrowMessage" class="form-label">Message to owner:</label>
                    <textarea id="borrowMessage" class="form-control" rows="4" placeholder="Add a personal message...">${defaultMessage}</textarea>
                </div>
            `,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Send Request',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#28a745',
            preConfirm: () => {
                const message = document.getElementById('borrowMessage').value;
                if (!message.trim()) {
                    Swal.showValidationMessage('Please enter a message');
                    return false;
                }
                return message;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('/borrow/{{ item.id }}/request', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        startDate: selectedDates[0],
                        endDate: selectedDates[selectedDates.length - 1],
                        message: result.value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const itemName = {{ item.name|json_encode }};
                        const dateRange = formatDateRange(selectedDates);
                        Swal.fire('Request Sent Successfully!', `Your request for ${dateRange} for ${itemName} has been sent.`, 'success');
                        clearSelectedDates();
                    } else {
                        Swal.fire('Error!', data.error || 'Failed to send request.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'Failed to send request.', 'error');
                });
            }
        });
    }
}

function deleteItem(itemId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This will permanently delete this item!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`/api/items/${itemId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Deleted!', 'Item has been deleted.', 'success')
                        .then(() => {
                            window.location.href = '/browse';
                        });
                } else {
                    Swal.fire('Error!', data.error || 'Failed to delete item.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire('Error!', 'Failed to delete item.', 'error');
            });
        }
    });
}

function toggleCalendar() {
    const calendarSection = document.getElementById('calendarSection');
    if (calendarSection.style.display === 'none') {
        calendarSection.style.display = 'block';
        loadBorrowCalendar();
    } else {
        calendarSection.style.display = 'none';
    }
}

function changeBorrowMonth(direction) {
    borrowCurrentDate.setMonth(borrowCurrentDate.getMonth() + direction);
    loadBorrowCalendar();
    
    // Re-initialize tooltips after calendar renders with new month
    setTimeout(() => {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }, 100);
}

function changeCalendarMonth(direction) {
    viewCurrentDate.setMonth(viewCurrentDate.getMonth() + direction);
    loadViewCalendar();
}

function selectDate(dateStr, element) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const selectedDate = new Date(dateStr);
    
    // Don't allow selection of past dates
    if (selectedDate < today) {
        return;
    }
    
    // Range selection logic
    if (!rangeStartDate) {
        // First click - set start date
        rangeStartDate = dateStr;
        rangeEndDate = null;
        selectedDates = [dateStr];
        console.log('Start date selected:', dateStr);
    } else if (!rangeEndDate) {
        // Second click - set end date and fill range
        rangeEndDate = dateStr;
        
        const startDate = new Date(rangeStartDate);
        const endDate = new Date(rangeEndDate);
        
        // Ensure end date is after start date
        if (endDate < startDate) {
            // Swap if user clicked earlier date second
            const temp = rangeStartDate;
            rangeStartDate = rangeEndDate;
            rangeEndDate = temp;
        }
        
        // Fill in all dates between start and end
        selectedDates = fillDateRange(rangeStartDate, rangeEndDate);
        console.log('Range selected:', rangeStartDate, 'to', rangeEndDate, 'Total dates:', selectedDates.length);
    } else {
        // Third click - start new range
        rangeStartDate = dateStr;
        rangeEndDate = null;
        selectedDates = [dateStr];
        console.log('New range started:', dateStr);
    }
    
    updateCalendarHighlighting();
    updateSelectedDatesDisplay();
}

function fillDateRange(startDateStr, endDateStr) {
    const dates = [];
    const currentDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    
    // Ensure we include both start and end dates
    while (currentDate <= endDate) {
        dates.push(currentDate.toISOString().split('T')[0]);
        currentDate.setDate(currentDate.getDate() + 1);
    }
    
    console.log(`Filling range from ${startDateStr} to ${endDateStr}: ${dates.length} dates`, dates);
    return dates;
}

function updateCalendarHighlighting() {
    // Clear all previous selections
    const allButtons = document.querySelectorAll('.calendar-day');
    allButtons.forEach(button => {
        button.classList.remove('bg-primary', 'text-white', 'btn-warning', 'text-dark');
        if (!button.disabled && !button.classList.contains('btn-danger')) {
            // Only reset to success if it's not already reserved/on-loan
            const isReservedOrOnLoan = button.classList.contains('btn-warning') || button.classList.contains('btn-danger');
            if (!isReservedOrOnLoan) {
                button.classList.add('btn-success', 'text-white');
            }
        }
    });
    
    // Highlight selected dates with "Reserved" color (yellow warning)
    selectedDates.forEach(dateStr => {
        // Find all buttons and check their onclick attribute for the date
        const allButtons = document.querySelectorAll('.calendar-day');
        allButtons.forEach(button => {
            const onclickAttr = button.getAttribute('onclick');
            if (onclickAttr && onclickAttr.includes(`'${dateStr}'`)) {
                // Remove any existing styling
                button.classList.remove('btn-success', 'text-white', 'bg-primary');
                // Apply "Reserved" styling (same as existing reserved dates)
                button.classList.add('btn-warning', 'text-dark');
                
                // Add tooltip to show this is user's selection
                button.setAttribute('title', 'Selected for your request');
                button.setAttribute('data-bs-toggle', 'tooltip');
            }
        });
    });
    
    // Re-initialize tooltips for the new selections
    setTimeout(() => {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            // Dispose existing tooltip if any
            const existingTooltip = bootstrap.Tooltip.getInstance(tooltipTriggerEl);
            if (existingTooltip) {
                existingTooltip.dispose();
            }
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }, 50);
}

function clearSelectedDates() {
    selectedDates = [];
    rangeStartDate = null;
    rangeEndDate = null;
    updateCalendarHighlighting();
    updateSelectedDatesDisplay();
}

// Helper function to parse UTC dates without timezone conversion
function parseUTCDate(dateStr) {
    if (dateStr.includes('T')) {
        return new Date(dateStr.split('T')[0] + 'T12:00:00.000Z');
    } else {
        return new Date(dateStr + 'T12:00:00.000Z');
    }
}

function formatDate(dateStr) {
    const date = parseUTCDate(dateStr);
    return date.toLocaleDateString('en-US', { 
        weekday: 'short', 
        month: 'short', 
        day: 'numeric' 
    });
}

function updateSelectedDatesDisplay() {
    const selectedDatesEl = document.getElementById('borrowSelectedDates');
    const selectedDatesListEl = document.getElementById('borrowSelectedDatesList');
    const sendRequestBtn = document.getElementById('sendBorrowRequestBtn');
    
    if (selectedDates.length > 0) {
        selectedDatesEl.style.display = 'block';
        const sortedDates = selectedDates.sort();
        const startDate = sortedDates[0];
        const endDate = sortedDates[sortedDates.length - 1];
        
        if (selectedDatesListEl) {
            if (startDate === endDate) {
                selectedDatesListEl.textContent = formatDate(startDate);
            } else {
                selectedDatesListEl.textContent = `${formatDate(startDate)} to ${formatDate(endDate)}`;
            }
            
            // Add day count
            const dayCount = selectedDates.length;
            selectedDatesListEl.textContent += ` (${dayCount} day${dayCount !== 1 ? 's' : ''})`;
        } else {
            // Fallback if element doesn't exist
            selectedDatesEl.innerHTML = `<small class="text-success">${formatDate(startDate)} to ${formatDate(endDate)} (${selectedDates.length} days)</small>`;
        }
        
        if (sendRequestBtn) sendRequestBtn.disabled = false;
    } else {
        selectedDatesEl.style.display = 'block';
        if (!rangeStartDate) {
            selectedDatesEl.innerHTML = '<small class="text-muted">Click a start date to begin selection</small>';
        } else {
            selectedDatesEl.innerHTML = '<small class="text-info">Start date selected. Click an end date to complete range.</small>';
        }
        if (sendRequestBtn) sendRequestBtn.disabled = true;
    }
}

function loadBorrowCalendar() {
    const year = borrowCurrentDate.getFullYear();
    const month = borrowCurrentDate.getMonth() + 1;
    
    // Update month header
    document.getElementById('borrowCurrentMonth').textContent = 
        borrowCurrentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
    
    // Fetch calendar data with cache busting
    console.log('=== CALENDAR DEBUG: Fetching calendar data ===');
    fetch(`/api/items/{{ item.id }}/calendar/${year}/${month}?user={{ currentUser.id }}&v=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            console.log('=== CALENDAR DEBUG: Calendar data received ===', data);
            console.log('=== CALENDAR DEBUG: isOwner in response:', data.isOwner);
            // Process availability data into a more usable format
            calendarData = {};
            if (data.availability && Array.isArray(data.availability)) {
                data.availability.forEach(item => {
                    calendarData[item.date] = item.status;
                });
            }
            // Process loan data to mark dates as unavailable
            if (data.loans && Array.isArray(data.loans)) {
                console.log('Processing loans:', data.loans);
                data.loans.forEach(loan => {
                    console.log('Processing loan:', loan);
                    // Skip completed loans - they don't affect availability
                    if (loan.status === 'completed') {
                        return;
                    }
                    
                    // Parse dates as UTC to avoid timezone issues
                    const startDate = new Date(loan.borrowedDate.split('T')[0] + 'T12:00:00.000Z');
                    const endDate = new Date(loan.expectedReturnDate.split('T')[0] + 'T12:00:00.000Z');
                    console.log('Loan dates:', { 
                        borrowedDate: loan.borrowedDate, 
                        expectedReturnDate: loan.expectedReturnDate,
                        startDate, 
                        endDate, 
                        status: loan.status 
                    });
                    
                    // For active loans (including overdue), extend availability check to today if overdue
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);
                    const actualEndDate = loan.status === 'active' && endDate < today ? today : endDate;
                    
                    // Use simple date string parsing to avoid timezone issues
                    const startDateStr = loan.borrowedDate.split('T')[0]; // Get YYYY-MM-DD
                    const endDateStr = loan.expectedReturnDate.split('T')[0]; // Get YYYY-MM-DD
                    
                    // Handle both single day and multi-day loans
                    for (let d = new Date(startDate); d <= actualEndDate; d.setDate(d.getDate() + 1)) {
                        const dateKey = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
                        console.log('Setting calendar data for date:', dateKey, 'status:', loan.status);
                        
                        // Mark dates based on loan status
                        if (loan.status === 'reserved') {
                            calendarData[dateKey] = {
                                status: 'reserved',
                                borrower: loan.borrowerName || 'Reserved'
                            };
                        } else if (loan.status === 'active') {
                            calendarData[dateKey] = {
                                status: 'on-loan',
                                borrower: loan.borrowerName || 'On Loan'
                            };
                        } else if (loan.status === 'overdue') {
                            calendarData[dateKey] = {
                                status: 'overdue',
                                borrower: loan.borrowerName || 'Overdue'
                            };
                        }
                    }
                });
            }
            console.log('Final calendar data:', calendarData);
            renderBorrowCalendar();
            // Initialize tooltips for borrow calendar
            setTimeout(() => {
                const tooltipTriggerList = [].slice.call(document.querySelectorAll('#borrowCalendarGrid [data-bs-toggle="tooltip"]'));
                tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl);
                });
            }, 100);
        })
        .catch(error => {
            console.error('Error loading calendar:', error);
            calendarData = {};
            renderBorrowCalendar();
        });
}

function loadViewCalendar() {
    const year = viewCurrentDate.getFullYear();
    const month = viewCurrentDate.getMonth() + 1;
    
    // Update month header
    document.getElementById('calendarCurrentMonth').textContent = 
        viewCurrentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
    
    // Fetch calendar data
    fetch(`/api/items/{{ item.id }}/calendar/${year}/${month}?user={{ currentUser.id }}`)
        .then(response => response.json())
        .then(data => {
            // Process availability data into a more usable format
            viewCalendarData = {};
            if (data.availability && Array.isArray(data.availability)) {
                data.availability.forEach(item => {
                    viewCalendarData[item.date] = item.status;
                });
            }
            // Process loan data to mark dates as unavailable and store borrower info
            if (data.loans && Array.isArray(data.loans)) {
                data.loans.forEach(loan => {
                    // Skip completed loans - they don't affect availability
                    if (loan.status === 'completed') {
                        return;
                    }
                    
                    const startDate = new Date(loan.borrowedDate.split('T')[0] + 'T12:00:00.000Z');
                    const endDate = new Date(loan.expectedReturnDate.split('T')[0] + 'T12:00:00.000Z');
                    
                    // For active loans (including overdue), extend availability check to today if overdue
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);
                    const actualEndDate = loan.status === 'active' && endDate < today ? today : endDate;
                    
                    for (let d = new Date(startDate); d <= actualEndDate; d.setDate(d.getDate() + 1)) {
                        const dateKey = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
                        
                        // Set status and borrower info based on loan status
                        if (loan.status === 'reserved') {
                            viewCalendarData[dateKey] = {
                                status: 'reserved',
                                borrower: loan.displayName || loan.borrowerName || 'Reserved'
                            };
                        } else if (loan.status === 'active') {
                            viewCalendarData[dateKey] = {
                                status: 'on-loan',
                                borrower: loan.displayName || loan.borrowerName || 'On Loan'
                            };
                        } else if (loan.status === 'overdue') {
                            viewCalendarData[dateKey] = {
                                status: 'overdue',
                                borrower: loan.displayName || loan.borrowerName || 'Overdue'
                            };
                        }
                    }
                });
            }
            renderViewCalendar();
            // Initialize tooltips after calendar is rendered
            setTimeout(() => {
                const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl);
                });
            }, 100);
        })
        .catch(error => {
            console.error('Error loading calendar:', error);
            renderViewCalendar();
        });
}

function renderBorrowCalendar() {
    const tbody = document.getElementById('borrowCalendarGrid');
    if (!tbody) {
        console.error('Calendar grid element not found');
        return;
    }
    tbody.innerHTML = '';
    
    // Get first day of month and number of days
    const firstDay = new Date(borrowCurrentDate.getFullYear(), borrowCurrentDate.getMonth(), 1);
    const lastDay = new Date(borrowCurrentDate.getFullYear(), borrowCurrentDate.getMonth() + 1, 0);
    const startDate = firstDay.getDay();
    const daysInMonth = lastDay.getDate();
    
    const today = new Date();
    today.setHours(0, 0, 0, 0); // Reset time for accurate comparison
    let dayCounter = 1;
    
    // Calculate number of weeks needed (minimum 6 weeks for consistent layout)
    const weeks = 6;
    
    for (let week = 0; week < weeks; week++) {
        const row = document.createElement('tr');
        
        for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
            const cell = document.createElement('td');
            cell.className = 'text-center p-1';
            cell.style.height = '40px';
            cell.style.verticalAlign = 'middle';
            
            const dayIndex = week * 7 + dayOfWeek;
            
            if (dayIndex >= startDate && dayCounter <= daysInMonth) {
                const dayButton = document.createElement('button');
                dayButton.className = 'btn btn-sm calendar-day w-100';
                dayButton.textContent = dayCounter;
                dayButton.style.minHeight = '32px';
                
                const dateStr = `${borrowCurrentDate.getFullYear()}-${String(borrowCurrentDate.getMonth() + 1).padStart(2, '0')}-${String(dayCounter).padStart(2, '0')}`;
                
                // Check if it's today
                const currentDateObj = new Date(borrowCurrentDate.getFullYear(), borrowCurrentDate.getMonth(), dayCounter);
                currentDateObj.setHours(0, 0, 0, 0);
                const isToday = currentDateObj.getTime() === today.getTime();
                
                // Check if date is in the past
                const isPast = currentDateObj < today;
                
                if (isPast) {
                    dayButton.className += ' btn-outline-secondary';
                    dayButton.disabled = true;
                    dayButton.style.opacity = '0.5';
                } else {
                    // Apply availability status - check if this specific day has availability data
                    const dateKey = `${borrowCurrentDate.getFullYear()}-${String(borrowCurrentDate.getMonth() + 1).padStart(2, '0')}-${String(dayCounter).padStart(2, '0')}`;
                    const dayData = calendarData[dateKey];
                    const availability = typeof dayData === 'object' ? dayData.status : (dayData || 'available');
                    

                    
                    // Check if this date is already selected (for cross-month ranges)
                    const isSelectedDate = selectedDates && selectedDates.includes(dateStr);
                    
                    if (availability === 'available') {
                        if (isSelectedDate) {
                            // Apply "Reserved" styling for user's selected dates
                            dayButton.className += ' btn-warning text-dark';
                            dayButton.setAttribute('title', 'Selected for your request');
                            dayButton.setAttribute('data-bs-toggle', 'tooltip');
                        } else {
                            dayButton.className += ' btn-success text-white';
                        }
                        dayButton.setAttribute('onclick', `selectDate('${dateStr}', this)`);
                    } else if (availability === 'reserved') {
                        dayButton.className += ' btn-warning text-dark';
                        dayButton.disabled = true;
                        const borrower = typeof dayData === 'object' ? dayData.borrower : '';
                        if (borrower && borrower !== 'Reserved') {
                            dayButton.setAttribute('title', `Reserved by ${borrower} (click to chat)`);
                            dayButton.setAttribute('data-bs-toggle', 'tooltip');
                            dayButton.style.cursor = 'pointer';
                            dayButton.onclick = function() { 
                                const itemId = {{ item.id }};
                                window.location.href = `/item/${itemId}?chat=open`;
                            };
                        }
                    } else if (availability === 'on-loan') {
                        dayButton.className += ' btn-danger text-white';
                        dayButton.disabled = true;
                        const borrower = typeof dayData === 'object' ? dayData.borrower : '';
                        if (borrower && borrower !== 'On Loan') {
                            dayButton.setAttribute('title', `On loan to ${borrower}.\nClick to view your Item Chat.`);
                            dayButton.setAttribute('data-bs-toggle', 'tooltip');
                            dayButton.style.cursor = 'pointer';
                            dayButton.onclick = function() { 
                                const itemId = {{ item.id }};
                                window.location.href = `/item/${itemId}?chat=open`;
                            };
                        }
                    } else if (availability === 'overdue') {
                        dayButton.className += ' btn-danger text-white';
                        dayButton.style.backgroundColor = '#8B0000'; // Dark red for overdue
                        dayButton.style.borderColor = '#8B0000';
                        dayButton.disabled = true;
                        const borrower = typeof dayData === 'object' ? dayData.borrower : '';
                        if (borrower && borrower !== 'Overdue') {
                            dayButton.setAttribute('title', `Overdue - borrowed by ${borrower}.\nClick to view your Item Chat.`);
                            dayButton.setAttribute('data-bs-toggle', 'tooltip');
                            dayButton.style.cursor = 'pointer';
                            dayButton.onclick = function() { 
                                const itemId = {{ item.id }};
                                window.location.href = `/item/${itemId}?chat=open`;
                            };
                        }
                    }
                }
                
                if (isToday) {
                    dayButton.style.border = '2px solid #007bff';
                    dayButton.style.fontWeight = 'bold';
                }
                
                cell.appendChild(dayButton);
                dayCounter++;
            } else {
                // Empty cell for days before/after the month
                cell.innerHTML = '&nbsp;';
            }
            
            row.appendChild(cell);
        }
        
        tbody.appendChild(row);
    }
}

function renderViewCalendar() {
    const tbody = document.getElementById('viewCalendarGrid');
    if (!tbody) {
        console.error('View calendar grid element not found');
        return;
    }
    tbody.innerHTML = '';
    
    const firstDay = new Date(viewCurrentDate.getFullYear(), viewCurrentDate.getMonth(), 1);
    const lastDay = new Date(viewCurrentDate.getFullYear(), viewCurrentDate.getMonth() + 1, 0);
    const startDate = firstDay.getDay();
    const daysInMonth = lastDay.getDate();
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    let dayCounter = 1;
    
    const weeks = 6;
    
    for (let week = 0; week < weeks; week++) {
        const row = document.createElement('tr');
        
        for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
            const cell = document.createElement('td');
            cell.className = 'text-center p-1';
            cell.style.height = '40px';
            cell.style.verticalAlign = 'middle';
            
            const dayIndex = week * 7 + dayOfWeek;
            
            if (dayIndex >= startDate && dayCounter <= daysInMonth) {
                const dayButton = document.createElement('button');
                dayButton.className = 'btn btn-sm w-100';
                dayButton.textContent = dayCounter;
                dayButton.style.minHeight = '32px';
                dayButton.disabled = true;
                
                const currentDay = new Date(viewCurrentDate.getFullYear(), viewCurrentDate.getMonth(), dayCounter);
                currentDay.setHours(0, 0, 0, 0);
                const isToday = currentDay.getTime() === today.getTime();
                const isPast = currentDay < today;
                
                if (isPast) {
                    dayButton.className += ' btn-outline-secondary';
                    dayButton.style.opacity = '0.5';
                } else {
                    const dateKey = `${viewCurrentDate.getFullYear()}-${String(viewCurrentDate.getMonth() + 1).padStart(2, '0')}-${String(dayCounter).padStart(2, '0')}`;
                    const dayData = viewCalendarData[dateKey];
                    
                    if (!dayData || dayData === 'available') {
                        dayButton.className += ' btn-success';
                        dayButton.style.backgroundColor = '#28a745';
                        dayButton.style.borderColor = '#28a745';
                        dayButton.style.color = 'white';
                        dayButton.style.opacity = '1';
                    } else {
                        const status = typeof dayData === 'object' ? dayData.status : dayData;
                        const borrower = typeof dayData === 'object' ? dayData.borrower : '';
                        
                        if (status === 'reserved') {
                            dayButton.className += ' btn-warning';
                            dayButton.style.backgroundColor = '#ffc107';
                            dayButton.style.borderColor = '#ffc107';
                            dayButton.style.color = '#212529';
                            dayButton.style.opacity = '1';
                            if (borrower && borrower !== 'Reserved') {
                                dayButton.setAttribute('title', `Reserved by ${borrower} (click to chat)`);
                                dayButton.setAttribute('data-bs-toggle', 'tooltip');
                                dayButton.style.cursor = 'pointer';
                                dayButton.onclick = function() { 
                                    const itemId = {{ item.id }};
                                    window.location.href = `/item/${itemId}?chat=open`;
                                };
                            }
                        } else if (status === 'on-loan') {
                            dayButton.className += ' btn-danger';
                            dayButton.style.backgroundColor = '#dc3545';
                            dayButton.style.borderColor = '#dc3545';
                            dayButton.style.color = 'white';
                            dayButton.style.opacity = '1';
                            if (borrower && borrower !== 'On Loan') {
                                dayButton.setAttribute('title', `On loan to ${borrower}.\nClick to view your Item Chat.`);
                                dayButton.setAttribute('data-bs-toggle', 'tooltip');
                                dayButton.style.cursor = 'pointer';
                                dayButton.onclick = function() { 
                                    const itemId = {{ item.id }};
                                    window.location.href = `/item/${itemId}?chat=open`;
                                };
                            }
                        } else if (status === 'overdue') {
                            dayButton.className += ' btn-danger';
                            dayButton.style.backgroundColor = '#8B0000'; // Dark red for overdue
                            dayButton.style.borderColor = '#8B0000';
                            dayButton.style.color = 'white';
                            dayButton.style.opacity = '1';
                            if (borrower && borrower !== 'Overdue') {
                                dayButton.setAttribute('title', `Overdue - borrowed by ${borrower}`);
                                dayButton.setAttribute('data-bs-toggle', 'tooltip');
                            }
                        }
                    }
                }
                
                if (isToday) {
                    dayButton.style.border = '2px solid #007bff';
                }
                
                cell.appendChild(dayButton);
                dayCounter++;
            } else {
                cell.innerHTML = '&nbsp;';
            }
            
            row.appendChild(cell);
        }
        
        tbody.appendChild(row);
    }
}

// Chat functions
function initializeChat() {
    console.log('Initializing chat, conversationId:', conversationId);
    
    if (!conversationId) {
        console.log('No existing conversationId, starting new conversation...');
        // Start a new conversation
        fetch('/api/chat/start', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                itemId: {{ item.id }},
                ownerId: {{ item.owner }}
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Chat start response:', data);
            if (data.conversationId) {
                conversationId = data.conversationId;
                console.log('Conversation started with ID:', conversationId);
                loadMessages();
            } else {
                console.error('No conversationId in response:', data);
                showChatError('Failed to start conversation');
            }
        })
        .catch(error => {
            console.error('Error starting conversation:', error);
            showChatError('Error connecting to chat service');
        });
    } else {
        console.log('Using existing conversationId:', conversationId);
        loadMessages();
    }
}

function showChatError(message) {
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.innerHTML = `<div class="text-center text-danger py-4">
            <div class="mb-2"><i class="fas fa-exclamation-triangle fa-2x"></i></div>
            <p class="mb-0">${message}</p>
            <button class="btn btn-sm btn-outline-primary mt-2" onclick="initializeChat()">Try Again</button>
        </div>`;
    }
}

function loadMessages() {
    if (!conversationId) {
        console.error('Cannot load messages: no conversationId');
        return;
    }
    
    console.log('Loading messages for conversation:', conversationId);
    
    fetch(`/api/chat/${conversationId}/messages`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Messages loaded successfully:', data);
            displayMessages(data.messages || []);
        })
        .catch(error => {
            console.error('Error loading messages:', error);
            showChatError('Failed to load messages');
        });
}

function displayMessages(messages) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('chatMessages element not found');
        return;
    }
    
    chatMessages.innerHTML = '';
    
    if (!messages || messages.length === 0) {
        chatMessages.innerHTML = '<div class="no-messages text-center text-muted py-4"><p class="mb-0">No messages yet.</p></div>';
        return;
    }
    
    const currentUserId = {{ session.userId ?? 34 }}; // Demo fallback
    
    messages.forEach(message => {
        const messageCard = document.createElement('div');
        messageCard.className = 'card mb-2';
        
        const isCurrentUser = message.sender_id === currentUserId;
        const cardClass = isCurrentUser ? 'border-primary' : 'border-secondary';
        messageCard.classList.add(cardClass);
        
        let messageContent = '';
        if (message.audio_path && message.message_type === 'audio') {
            messageContent = `
                <div class="audio-message">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <audio controls class="w-100 mb-2">
                                <source src="${message.audio_path}" type="audio/webm">
                                Your browser does not support the audio element.
                            </audio>
                            ${message.transcription ? `<p class="transcription small mb-0 text-muted">${message.transcription}</p>` : ''}
                        </div>
                        ${message.sender_id === currentUserId ? `
                        <div class="dropdown">
                            <button class="btn btn-link btn-sm p-0" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-ellipsis-v text-muted"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="${message.audio_path}" download="audio_message_${message.id}.webm">
                                    <i class="fas fa-download me-2"></i>Download
                                </a></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="deleteAudioMessage(${message.id})">
                                    <i class="fas fa-trash me-2"></i>Delete
                                </a></li>
                            </ul>
                        </div>
                        ` : ''}
                    </div>
                </div>
            `;
        } else {
            messageContent = `<p class="mb-0">${message.text_content || 'Empty message'}</p>`;
        }
        
        const senderName = isCurrentUser ? 'You' : (message.sender_show_name || message.sender_first_name || 'User');
        const timeAgo = formatTimeAgo(new Date(message.created_at));
        
        messageCard.innerHTML = `
            <div class="card-body py-2">
                <div class="d-flex justify-content-between align-items-start mb-1">
                    <small class="text-muted fw-bold">${senderName}</small>
                    <small class="text-muted">${timeAgo}</small>
                </div>
                ${messageContent}
            </div>
        `;
        
        chatMessages.appendChild(messageCard);
    });
}

let isSendingMessage = false;

// Contextual help system for borrowing guidance
function checkForBorrowingKeywords(message) {
    const borrowingKeywords = [
        'borrow', 'rent', 'use', 'need', 'can i', 'may i', 'available', 
        'dates', 'when', 'pick up', 'return', 'lend', 'loan', 'tomorrow',
        'weekend', 'week', 'month', 'next', 'today'
    ];
    
    const lowerMessage = message.toLowerCase();
    return borrowingKeywords.some(keyword => lowerMessage.includes(keyword));
}

function showBorrowingHelp() {
    const banner = document.getElementById('borrowingHelpBanner');
    if (banner && banner.classList.contains('d-none')) {
        banner.classList.remove('d-none');
        // Auto-hide after 10 seconds if not dismissed
        setTimeout(() => {
            if (banner && !banner.classList.contains('d-none')) {
                dismissBorrowingHelp();
            }
        }, 10000);
    }
}

function dismissBorrowingHelp() {
    const banner = document.getElementById('borrowingHelpBanner');
    if (banner) {
        banner.classList.add('d-none');
        // Store dismissal to prevent showing again in this session
        sessionStorage.setItem('borrowingHelpDismissed', 'true');
    }
}

function sendTextMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) {
        console.log('No message to send');
        return;
    }
    
    // Check if message contains borrowing keywords and show help if not dismissed
    if (checkForBorrowingKeywords(message) && !sessionStorage.getItem('borrowingHelpDismissed')) {
        showBorrowingHelp();
    }
    
    if (!conversationId) {
        console.error('Cannot send message: no conversationId');
        LocalLendables.showErrorToast('Chat Error', 'Chat not initialized. Please try reopening the chat window.');
        return;
    }
    
    // Prevent duplicate submissions
    if (isSendingMessage) {
        console.log('Already sending message, ignoring duplicate request');
        return;
    }
    
    console.log('Sending message:', message, 'to conversation:', conversationId);
    
    // Set flag to prevent duplicates
    isSendingMessage = true;
    
    // Disable input while sending
    messageInput.disabled = true;
    
    fetch(`/api/chat/${conversationId}/message`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            content: message
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Message sent successfully:', data);
        if (data.success) {
            messageInput.value = '';
            loadMessages();
        } else {
            LocalLendables.showErrorToast('Message Failed', data.error || 'Unknown error occurred while sending message.');
        }
    })
    .catch(error => {
        console.error('Error sending message:', error);
        LocalLendables.showErrorToast('Connection Error', 'Error sending message. Please check your connection and try again.');
    })
    .finally(() => {
        messageInput.disabled = false;
        isSendingMessage = false; // Reset flag to allow future messages
        messageInput.focus();
    });
}

function handleMessageKeyPress(event) {
    if (event.key === 'Enter') {
        sendTextMessage();
    }
}

function startRecording() {
    if (isRecording) return;
    
    navigator.mediaDevices.getUserMedia({ 
        audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true,
            sampleRate: 44100
        }
    })
        .then(stream => {
            // Create MediaRecorder with optimized settings per Audio Canon
            mediaRecorder = new MediaRecorder(stream, {
                mimeType: 'audio/webm;codecs=opus',
                audioBitsPerSecond: 128000
            });
            const audioChunks = [];
            
            mediaRecorder.addEventListener('dataavailable', event => {
                audioChunks.push(event.data);
            });
            
            mediaRecorder.addEventListener('stop', () => {
                currentAudioBlob = new Blob(audioChunks, { type: 'audio/webm;codecs=opus' });
                stream.getTracks().forEach(track => track.stop());
                
                // Show playback controls
                showAudioPreview(currentAudioBlob);
            });
            
            mediaRecorder.start(1000); // Collect data every second per Audio Canon
            isRecording = true;
            recordingStartTime = Date.now();
            
            // Update UI
            document.getElementById('recordBtn').style.display = 'none';
            document.getElementById('stopBtn').style.display = 'inline-block';
            document.getElementById('recordingStatus').style.display = 'block';
            
            // Start timer
            updateRecordingTimer();
            recordingTimer = setInterval(updateRecordingTimer, 100);
            
            // Auto-stop recording after 30 seconds to prevent butt-dialing
            setTimeout(() => {
                if (mediaRecorder && mediaRecorder.state === 'recording') {
                    stopRecording();
                    LocalLendables.showWarningToast('Recording Limit', 'Recording automatically stopped after 30 seconds to prevent accidental long recordings.');
                }
            }, 30000);
        })
        .catch(error => {
            console.error('Error accessing microphone:', error);
            LocalLendables.showErrorToast('Microphone Access', 'Could not access microphone. Please check your browser permissions.');
        });
}

function stopRecording() {
    if (!isRecording || !mediaRecorder) return;
    
    mediaRecorder.stop();
    isRecording = false;
    
    // Clear timer
    if (recordingTimer) {
        clearInterval(recordingTimer);
        recordingTimer = null;
    }
    
    // Update UI
    document.getElementById('recordBtn').style.display = 'inline-block';
    document.getElementById('stopBtn').style.display = 'none';
    document.getElementById('recordingStatus').style.display = 'none';
}

function updateRecordingTimer() {
    if (!recordingStartTime) return;
    
    const elapsed = Date.now() - recordingStartTime;
    const seconds = Math.floor(elapsed / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    
    document.getElementById('recordingTime').textContent = 
        `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

function showAudioPreview(audioBlob) {
    const audioPreview = document.getElementById('audioPreview');
    const audioPlayback = document.getElementById('audioPlayback');
    
    // Create audio URL
    const audioUrl = URL.createObjectURL(audioBlob);
    audioPlayback.src = audioUrl;
    
    // Show preview section
    audioPreview.style.display = 'block';
}

function sendAudioMessage() {
    if (!currentAudioBlob || !conversationId) return;
    
    const formData = new FormData();
    formData.append('recording', currentAudioBlob, 'recording.webm');
    
    document.getElementById('sendAudioBtn').disabled = true;
    document.getElementById('sendAudioBtn').textContent = 'Sending...';
    
    fetch(`/api/chat/${conversationId}/audio`, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Clear preview
            cancelAudioMessage();
            loadMessages();
        } else {
            LocalLendables.showErrorToast('Audio Failed', 'Failed to send audio message. Please try again.');
        }
    })
    .catch(error => {
        console.error('Error sending audio:', error);
        LocalLendables.showErrorToast('Audio Error', 'Error sending audio message. Please check your connection.');
    })
    .finally(() => {
        document.getElementById('sendAudioBtn').disabled = false;
        document.getElementById('sendAudioBtn').textContent = 'Send Audio';
    });
}

function cancelAudioMessage() {
    if (currentAudioBlob) {
        URL.revokeObjectURL(document.getElementById('audioPlayback').src);
        currentAudioBlob = null;
    }
    
    document.getElementById('audioPreview').style.display = 'none';
}

function formatTimeAgo(date) {
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);
    
    if (diffInSeconds < 60) {
        return 'Just now';
    } else if (diffInSeconds < 3600) {
        const minutes = Math.floor(diffInSeconds / 60);
        return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
    } else if (diffInSeconds < 86400) {
        const hours = Math.floor(diffInSeconds / 3600);
        return `${hours} hour${hours > 1 ? 's' : ''} ago`;
    } else {
        return date.toLocaleDateString();
    }
}

function sendBorrowRequest() {
    // Use selected dates from range selection
    const datesToUse = selectedDates;
    
    if (datesToUse.length === 0) {
        LocalLendables.showErrorToast('Selection Required', 'Please select at least one date for your borrow request.');
        return;
    }
    
    // Show modal for message input
    showBorrowMessageModal(datesToUse);
}

function formatDateRange(dates) {
    if (!dates || dates.length === 0) return 'No dates selected';
    
    const sortedDates = dates.sort();
    const startDate = sortedDates[0];
    const endDate = sortedDates[sortedDates.length - 1];
    
    if (startDate === endDate) {
        return formatDate(startDate);
    } else {
        return `${formatDate(startDate)} to ${formatDate(endDate)}`;
    }
}

function showBorrowMessageModal(selectedDates) {
    // Create the modal HTML
    const modalHtml = `
        <div class="modal fade" id="borrowMessageModal" tabindex="-1" aria-labelledby="borrowMessageModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="borrowMessageModalLabel">
                            <i class="fas fa-paper-plane me-2"></i>Send Borrow Request
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <p class="text-muted">
                                <i class="fas fa-calendar-alt me-2"></i>
                                <strong>Selected dates:</strong> ${formatDateRange(selectedDates)}
                            </p>
                        </div>
                        <div class="mb-3">
                            <label for="borrowMessage" class="form-label">Message to owner:</label>
                            <textarea class="form-control" id="borrowMessage" rows="4" 
                                placeholder="Loading default message...">Loading default message...</textarea>
                        </div>
                        
                        <!-- Audio Recording Option -->
                        <div class="mb-3">
                            <label class="form-label">Or record a voicemail:</label>
                            <div class="audio-controls-borrow">
                                <div class="btn-group mb-2" role="group">
                                    <button id="recordBorrowBtn" class="btn btn-outline-danger btn-sm" type="button" onclick="startBorrowRecording()">
                                        <i class="fas fa-microphone"></i> Record Voicemail
                                    </button>
                                    <button id="stopBorrowBtn" class="btn btn-outline-success btn-sm" type="button" onclick="stopBorrowRecording()" style="display: none;">
                                        <i class="fas fa-stop"></i> Stop Recording
                                    </button>
                                </div>
                                
                                <div id="borrowRecordingStatus" class="text-muted small mb-2" style="display: none;">
                                    <i class="fas fa-circle text-danger blink"></i> Recording... <span id="borrowRecordingTime">0:00</span>
                                </div>
                                
                                <div id="borrowAudioPreview" class="audio-preview" style="display: none;">
                                    <div class="d-flex align-items-center gap-2 p-2 bg-light rounded">
                                        <audio id="borrowAudioPlayback" controls class="flex-grow-1"></audio>
                                        <button class="btn btn-outline-secondary btn-sm" onclick="cancelBorrowAudio()">
                                            <i class="fas fa-times"></i> Remove
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" onclick="submitBorrowRequest()">
                            <i class="fas fa-paper-plane me-2"></i>Send Request
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('borrowMessageModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Store selected dates for later use
    window.currentBorrowDates = selectedDates;
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('borrowMessageModal'));
    modal.show();
    
    // Load default message template from database
    loadDefaultBorrowMessage();
}

function loadDefaultBorrowMessage() {
    fetch('/api/content/borrow-message-template')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.message) {
                const messageTextarea = document.getElementById('borrowMessage');
                if (messageTextarea) {
                    messageTextarea.value = data.message;
                    messageTextarea.placeholder = data.message;
                }
            }
        })
        .catch(error => {
            console.error('Error loading default message:', error);
            // Fallback to hardcoded message
            const messageTextarea = document.getElementById('borrowMessage');
            if (messageTextarea) {
                const fallbackMessage = 'Hi! I would like to borrow your item for the selected dates. I\'ll take great care of it and return it in perfect condition.';
                messageTextarea.value = fallbackMessage;
                messageTextarea.placeholder = fallbackMessage;
            }
        });
}

function submitBorrowRequest() {
    const message = document.getElementById('borrowMessage').value;
    const selectedDates = window.currentBorrowDates;
    const audioBlob = window.currentBorrowAudio;
    
    if (!selectedDates || selectedDates.length === 0) {
        LocalLendables.showErrorToast('Selection Required', 'No dates selected for your request.');
        return;
    }
    
    // Check if we have either text message or audio
    if (!message.trim() && !audioBlob) {
        LocalLendables.showErrorToast('Message Required', 'Please enter a message or record a voicemail to complete your request.');
        return;
    }
    
    // Convert dates to start/end format
    const sortedDates = selectedDates.sort();
    const startDate = sortedDates[0];
    const endDate = sortedDates[sortedDates.length - 1];
    
    // Disable the button
    const sendBtn = document.querySelector('button[onclick="submitBorrowRequest()"]');
    if (sendBtn) {
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Sending...';
    }
    
    if (audioBlob) {
        // Send with audio
        const formData = new FormData();
        formData.append('itemId', {{ item.id }});
        formData.append('startDate', startDate);
        formData.append('endDate', endDate);
        formData.append('message', message);
        formData.append('audio', audioBlob, 'borrow-request.webm');
        
        fetch('/api/borrow-requests', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(handleBorrowResponse)
        .catch(handleBorrowError)
        .finally(() => resetBorrowButton(sendBtn));
    } else {
        // Send text only
        const requestData = {
            itemId: {{ item.id }},
            startDate: startDate,
            endDate: endDate,
            message: message
        };
        
        fetch('/api/borrow-requests', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(handleBorrowResponse)
        .catch(handleBorrowError)
        .finally(() => resetBorrowButton(sendBtn));
    }
}

function handleBorrowResponse(data) {
    if (data.success) {
        // Get the item name and dates for success message
        const itemName = {{ item.name|json_encode }};
        const selectedDates = window.currentBorrowDates || [];
        const dateRange = formatDateRange(selectedDates);
        
        // Show success notification
        LocalLendables.showSuccessToast(
            'Request Sent Successfully!',
            `Your request for ${dateRange} for ${itemName} has been sent to the owner.`
        );
        
        // Close modal first
        const modal = bootstrap.Modal.getInstance(document.getElementById('borrowMessageModal'));
        if (modal) {
            modal.hide();
        }
        
        // Wait for modal to close, then scroll to top and clean URL
        setTimeout(() => {
            window.scrollTo({ top: 0, behavior: 'smooth' });
            document.documentElement.scrollTop = 0;
            document.body.scrollTop = 0;
            
            // Clean URL to prevent calendar from reopening
            const newUrl = window.location.pathname;
            window.history.replaceState({}, document.title, newUrl);
        }, 300);
        
        // Clear selections and audio
        selectedDates = [];
        loanSelectedDates = [];
        window.currentBorrowAudio = null;
        clearLoanSelectedDates();
        
        // Close any open panels
        const borrowPanel = document.getElementById('borrowPanel');
        if (borrowPanel) borrowPanel.style.display = 'none';
        const calendarPanel = document.getElementById('calendarPanel');
        if (calendarPanel) calendarPanel.style.display = 'none';
        
    } else {
        LocalLendables.showErrorToast('Request Failed', data.error || 'Unknown error occurred while sending your request.');
    }
}

function handleBorrowError(error) {
    console.error('Error:', error);
    LocalLendables.showErrorToast('Network Error', 'Network error sending request. Please check your connection and try again.');
}

function resetBorrowButton(sendBtn) {
    if (sendBtn) {
        sendBtn.disabled = false;
        sendBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Request';
    }
}

// Borrow request audio recording functions
let borrowMediaRecorder = null;
let borrowRecordingStartTime = null;
let borrowRecordingTimer = null;
let isBorrowRecording = false;

function startBorrowRecording() {
    if (isBorrowRecording) return;
    
    navigator.mediaDevices.getUserMedia({ 
        audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true,
            sampleRate: 44100
        }
    })
    .then(stream => {
        borrowMediaRecorder = new MediaRecorder(stream, {
            mimeType: 'audio/webm;codecs=opus',
            audioBitsPerSecond: 128000
        });
        const audioChunks = [];
        
        borrowMediaRecorder.addEventListener('dataavailable', event => {
            audioChunks.push(event.data);
        });
        
        borrowMediaRecorder.addEventListener('stop', () => {
            window.currentBorrowAudio = new Blob(audioChunks, { type: 'audio/webm;codecs=opus' });
            stream.getTracks().forEach(track => track.stop());
            showBorrowAudioPreview(window.currentBorrowAudio);
        });
        
        borrowMediaRecorder.start(1000);
        isBorrowRecording = true;
        borrowRecordingStartTime = Date.now();
        
        // Update UI
        document.getElementById('recordBorrowBtn').style.display = 'none';
        document.getElementById('stopBorrowBtn').style.display = 'inline-block';
        document.getElementById('borrowRecordingStatus').style.display = 'block';
        
        // Start timer
        updateBorrowRecordingTimer();
        borrowRecordingTimer = setInterval(updateBorrowRecordingTimer, 100);
        
        // Auto-stop recording after 30 seconds to prevent butt-dialing
        setTimeout(() => {
            if (borrowMediaRecorder && borrowMediaRecorder.state === 'recording') {
                stopBorrowRecording();
                LocalLendables.showWarningToast('Recording Limit', 'Recording automatically stopped after 30 seconds to prevent accidental long recordings.');
            }
        }, 30000);
    })
    .catch(error => {
        console.error('Error accessing microphone:', error);
        LocalLendables.showErrorToast('Microphone Access', 'Could not access microphone. Please check your browser permissions and try again.');
    });
}

function stopBorrowRecording() {
    if (!isBorrowRecording || !borrowMediaRecorder) return;
    
    borrowMediaRecorder.stop();
    isBorrowRecording = false;
    
    if (borrowRecordingTimer) {
        clearInterval(borrowRecordingTimer);
        borrowRecordingTimer = null;
    }
    
    // Update UI
    document.getElementById('recordBorrowBtn').style.display = 'inline-block';
    document.getElementById('stopBorrowBtn').style.display = 'none';
    document.getElementById('borrowRecordingStatus').style.display = 'none';
}

function updateBorrowRecordingTimer() {
    if (!borrowRecordingStartTime) return;
    
    const elapsed = Date.now() - borrowRecordingStartTime;
    const seconds = Math.floor(elapsed / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    
    document.getElementById('borrowRecordingTime').textContent = 
        `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

function showBorrowAudioPreview(audioBlob) {
    const audioPlayback = document.getElementById('borrowAudioPlayback');
    const audioPreview = document.getElementById('borrowAudioPreview');
    
    audioPlayback.src = URL.createObjectURL(audioBlob);
    audioPreview.style.display = 'block';
}

function cancelBorrowAudio() {
    if (window.currentBorrowAudio) {
        URL.revokeObjectURL(document.getElementById('borrowAudioPlayback').src);
        window.currentBorrowAudio = null;
    }
    
    document.getElementById('borrowAudioPreview').style.display = 'none';
}

// Event listeners for text message input
document.addEventListener('DOMContentLoaded', function() {
    const messageInput = document.getElementById('messageInput');
    if (messageInput) {
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendTextMessage();
            }
        });
    }
    
    // Check URL parameters and hash for auto-opening sections
    const urlParams = new URLSearchParams(window.location.search);
    const hash = window.location.hash;
    
    // Auto-open chat if ?chat=open parameter is present
    if (urlParams.get('chat') === 'open') {
        setTimeout(() => {
            const chatPanel = document.getElementById('chatPanel');
            if (chatPanel && chatPanel.style.display === 'none') {
                console.log('Auto-opening chat due to URL parameter');
                toggleChatPanel();
            }
        }, 100);
    }
    
    // Auto-display chat for "Asking for" items with existing conversations
    {% if item.isRequest and existingConversation %}
    setTimeout(() => {
        const chatPanel = document.getElementById('chatPanel');
        if (chatPanel && chatPanel.style.display === 'none') {
            console.log('Auto-opening chat for Asking for item with existing conversation');
            toggleChatPanel();
        }
    }, 300);
    {% endif %}
    
    // Handle chat section via hash
    if (hash === '#chat-section') {
        setTimeout(() => {
            const chatPanel = document.getElementById('chatPanel');
            if (chatPanel && chatPanel.style.display === 'none') {
                toggleChatPanel();
                // Scroll to chat section after opening
                setTimeout(() => {
                    chatPanel.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 100);
            }
        }, 300);
    }
    
    if (urlParams.get('chat') === 'open') {
        // Auto-open chat dropdown with delay to ensure DOM is ready
        setTimeout(() => {
            const chatPanel = document.getElementById('chatPanel');
            if (chatPanel && chatPanel.style.display === 'none') {
                toggleChatPanel();
                // Scroll to chat section after opening
                setTimeout(() => {
                    chatPanel.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 100);
            }
        }, 300);
    } else if (urlParams.get('borrow') === 'open') {
        // Auto-open borrow panel section (same as clicking the Borrow button)
        setTimeout(() => {
            const borrowPanel = document.getElementById('borrowPanel');
            if (borrowPanel && borrowPanel.style.display === 'none') {
                toggleBorrowPanel();
                // Scroll to borrow section after opening
                setTimeout(() => {
                    borrowPanel.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 200);
            }
        }, 300);
    } else if (urlParams.get('calendar') === 'open') {
        // Auto-open calendar modal (same as clicking the Calendar & Availability button)
        setTimeout(() => {
            openCalendarModal();
        }, 300);
    }
    
    // Clean URL after opening sections
    if (urlParams.get('chat') || urlParams.get('borrow') || urlParams.get('calendar')) {
        const newUrl = window.location.pathname;
        window.history.replaceState({}, document.title, newUrl);
    }
});

// Increment view count when page loads
document.addEventListener('DOMContentLoaded', function() {
    fetch('/api/items/{{ item.id }}/view', {
        method: 'POST'
    });
});

// Load loan calendar data when modal is opened
document.addEventListener('DOMContentLoaded', function() {
    const loanCalendarModal = document.getElementById('loanCalendarModal');
    if (loanCalendarModal) {
        loanCalendarModal.addEventListener('show.bs.modal', function () {
            loadLoanCalendar();
        });
    }
});

function loadLoanCalendar() {
    const content = document.getElementById('loanCalendarContent');
    content.innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading loan calendar...</p>
        </div>
    `;
    
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    
    fetch(`/api/items/{{ item.id }}/calendar/${year}/${month}?user={{ currentUser.id }}`)
        .then(response => {
            console.log('Calendar API response status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('Calendar API data received:', data);
            renderLoanCalendar(data.loans || []);
        })
        .catch(error => {
            console.error('Error loading loan calendar:', error);
            content.innerHTML = '<div class="alert alert-danger">Failed to load loan calendar data.</div>';
        });
}

function renderLoanCalendar(loans) {
    console.log('renderLoanCalendar called with loans:', loans);
    const content = document.getElementById('loanCalendarContent');
    
    if (!content) {
        console.error('loanCalendarContent element not found');
        return;
    }
    
    if (loans.length === 0) {
        console.log('No loans found, showing calendar for booking');
        content.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-calendar-alt fa-3x mb-3"></i>
                        <h5>No Upcoming Reservations</h5>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Select a date span to ask the Owner, to borrow?</h6>
                        </div>
                        <div class="card-body">
                            <div class="calendar-container">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <button class="btn btn-sm btn-outline-secondary" onclick="changeLoanMonth(-1)">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <h6 id="calendarMonth" class="mb-0"></h6>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="changeLoanMonth(1)">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                </div>
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th class="text-center">S</th>
                                            <th class="text-center">M</th>
                                            <th class="text-center">T</th>
                                            <th class="text-center">W</th>
                                            <th class="text-center">T</th>
                                            <th class="text-center">F</th>
                                            <th class="text-center">S</th>
                                        </tr>
                                    </thead>
                                    <tbody id="loanCalendarGrid">
                                    </tbody>
                                </table>
                            </div>
                            <div id="loanSelectedDates" style="display: none;" class="mt-3">
                                <div class="alert alert-info">
                                    <strong>Selected dates:</strong> <span id="loanSelectedDatesList"></span>
                                </div>
                                <button class="btn btn-primary btn-sm" onclick="proceedToBorrow()">
                                    Send Borrow Request
                                </button>
                                <button class="btn btn-outline-secondary btn-sm ms-2" onclick="clearLoanSelectedDates()">
                                    Clear Selection
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    
    // Set the booking calendar in both sections
    document.getElementById('loanCalendarContent').innerHTML = bookingCalendarHtml;
    
    // Also show it in the main calendar section if it exists
    const calendarGrid = document.getElementById('calendarGrid');
    if (calendarGrid) {
        calendarGrid.innerHTML = bookingCalendarHtml;
    }
        
    // Initialize calendar for loan booking
    initializeLoanCalendar();
    return;
    }
    
    let html = '<div class="timeline">';
    
    loans.forEach(loan => {
        const borrowedDate = new Date(loan.borrowedDate).toLocaleDateString();
        const expectedReturnDate = new Date(loan.expectedReturnDate).toLocaleDateString();
        const actualReturnDate = loan.actualReturnDate ? new Date(loan.actualReturnDate).toLocaleDateString() : null;
        
        let statusBadge = '';
        let statusClass = '';
        
        if (loan.status === 'completed') {
            statusBadge = '<span class="badge bg-success">Completed</span>';
            statusClass = 'border-success';
        } else if (loan.status === 'active') {
            statusBadge = '<span class="badge bg-warning">Active Loan</span>';
            statusClass = 'border-warning';
        } else {
            statusBadge = '<span class="badge bg-primary">Reserved</span>';
            statusClass = 'border-primary';
        }
        
        html += `
            <div class="card mb-3 ${statusClass}" style="border-left: 4px solid;">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h6 class="card-title mb-0">
                            ${loan.borrowerName || 'Unknown Borrower'}
                        </h6>
                        ${statusBadge}
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <small class="text-muted">Borrowed Date:</small>
                            <div><strong>${borrowedDate}</strong></div>
                        </div>
                        <div class="col-md-6">
                            <small class="text-muted">Expected Return:</small>
                            <div><strong>${expectedReturnDate}</strong></div>
                        </div>
                    </div>
                    ${actualReturnDate ? `
                        <div class="mt-2">
                            <small class="text-muted">Actual Return Date:</small>
                            <div><strong>${actualReturnDate}</strong></div>
                        </div>
                    ` : ''}
                    ${loan.price ? `
                        <div class="mt-2">
                            <small class="text-muted">Price:</small>
                            <div><strong>$${loan.price}</strong></div>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    content.innerHTML = html;
}

// Loan calendar variables
let loanCurrentDate = new Date();
let loanSelectedDates = [];

// Initialize loan calendar
function initializeLoanCalendar() {
    renderBookingCalendar();
}

// Change month in loan calendar
function changeLoanMonth(direction) {
    loanCurrentDate.setMonth(loanCurrentDate.getMonth() + direction);
    renderBookingCalendar();
}

// Render booking calendar
function renderBookingCalendar() {
    const monthEl = document.getElementById('calendarMonth');
    const gridEl = document.getElementById('loanCalendarGrid');
    
    if (!monthEl || !gridEl) return;
    
    // Update month header
    monthEl.textContent = loanCurrentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
    
    // Clear grid
    gridEl.innerHTML = '';
    
    // Get first day of month and number of days
    const firstDay = new Date(loanCurrentDate.getFullYear(), loanCurrentDate.getMonth(), 1);
    const lastDay = new Date(loanCurrentDate.getFullYear(), loanCurrentDate.getMonth() + 1, 0);
    const startDate = firstDay.getDay();
    const daysInMonth = lastDay.getDate();
    
    const today = new Date();
    let dayCounter = 1;
    
    // Calculate number of weeks needed
    const totalCells = Math.ceil((startDate + daysInMonth) / 7) * 7;
    const weeks = totalCells / 7;
    
    for (let week = 0; week < weeks; week++) {
        const row = document.createElement('tr');
        
        for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
            const cell = document.createElement('td');
            cell.className = 'text-center p-1';
            cell.style.height = '35px';
            
            const dayIndex = week * 7 + dayOfWeek;
            
            if (dayIndex >= startDate && dayCounter <= daysInMonth) {
                const dayButton = document.createElement('button');
                dayButton.className = 'btn btn-sm w-100 loan-calendar-day';
                dayButton.textContent = dayCounter;
                dayButton.style.minHeight = '30px';
                
                const dateStr = `${loanCurrentDate.getFullYear()}-${String(loanCurrentDate.getMonth() + 1).padStart(2, '0')}-${String(dayCounter).padStart(2, '0')}`;
                
                // Check if date is in the past
                const currentDateObj = new Date(loanCurrentDate.getFullYear(), loanCurrentDate.getMonth(), dayCounter);
                const isPast = currentDateObj < today;
                
                if (isPast) {
                    dayButton.disabled = true;
                    dayButton.classList.add('btn-outline-secondary');
                    dayButton.style.opacity = '0.5';
                } else {
                    dayButton.classList.add('btn-outline-success');
                    dayButton.onclick = () => toggleLoanDate(dateStr, dayButton);
                }
                
                // Check if date is selected
                if (loanSelectedDates.includes(dateStr)) {
                    dayButton.classList.remove('btn-outline-success');
                    dayButton.classList.add('btn-primary', 'text-white');
                }
                
                cell.appendChild(dayButton);
                dayCounter++;
            }
            
            row.appendChild(cell);
        }
        
        gridEl.appendChild(row);
    }
}

// Toggle date selection in loan calendar
function toggleLoanDate(dateStr, element) {
    const index = loanSelectedDates.indexOf(dateStr);
    
    if (index > -1) {
        loanSelectedDates.splice(index, 1);
        element.classList.remove('btn-primary', 'text-white');
        element.classList.add('btn-outline-success');
    } else {
        loanSelectedDates.push(dateStr);
        element.classList.remove('btn-outline-success');
        element.classList.add('btn-primary', 'text-white');
    }
    
    updateLoanSelectedDatesDisplay();
}

// Update selected dates display
function updateLoanSelectedDatesDisplay() {
    const selectedDatesEl = document.getElementById('loanSelectedDates');
    const selectedDatesListEl = document.getElementById('loanSelectedDatesList');
    
    if (!selectedDatesEl || !selectedDatesListEl) return;
    
    if (loanSelectedDates.length > 0) {
        selectedDatesEl.style.display = 'block';
        selectedDatesListEl.textContent = formatDateRange(loanSelectedDates);
    } else {
        selectedDatesEl.style.display = 'none';
    }
}

// Clear selected dates
function clearLoanSelectedDates() {
    loanSelectedDates = [];
    const selectedElements = document.querySelectorAll('.loan-calendar-day.btn-primary');
    selectedElements.forEach(el => {
        el.classList.remove('btn-primary', 'text-white');
        el.classList.add('btn-outline-success');
    });
    updateLoanSelectedDatesDisplay();
}

// Proceed to borrow with selected dates
function proceedToBorrow() {
    if (loanSelectedDates.length === 0) {
        LocalLendables.showErrorToast('Date Selection Required', 'Please select at least one date for your borrow request.');
        return;
    }
    
    // Set the selected dates for the calendar flow
    selectedDates = [...loanSelectedDates];
    window.currentBorrowDates = [...loanSelectedDates];
    
    // Send the borrow request using the modal flow
    sendBorrowRequest();
}

// Open chat function - now opens modal instead of new window
function openChat() {
    const itemId = {{ item.id }};
    const ownerId = {{ item.owner }};
    const currentUserId = {{ session.userId ?? 1 }}; // Demo fallback
    
    // Determine who is the borrower (current user if not owner)
    const borrowerId = (currentUserId === ownerId) ? 1 : currentUserId; // Demo fallback for owner viewing
    
    // Load chat content into modal
    const chatModal = new bootstrap.Modal(document.getElementById('chatModal'));
    
    // Set loading state
    document.getElementById('chatModalBody').innerHTML = '<div class="text-center p-4"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div>';
    
    // Load chat content
    fetch(`/chat/${itemId}/${ownerId}/${borrowerId}?user=${currentUserId}&modal=true`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('chatModalBody').innerHTML = html;
            
            // Extract conversation ID from the loaded HTML content
            const modalBody = document.getElementById('chatModalBody');
            
            // Look for the conversation ID from the data attribute
            let modalConversationId = null;
            const conversationData = modalBody.querySelector('#chat-conversation-data');
            if (conversationData) {
                modalConversationId = parseInt(conversationData.dataset.conversationId);
            }
            
            // Set the conversation ID and load messages using existing functions
            if (modalConversationId) {
                conversationId = modalConversationId;
                console.log('Modal chat initialized with conversation ID:', conversationId);
                
                // Use the existing loadMessages function from the main page
                setTimeout(() => {
                    if (typeof loadMessages === 'function') {
                        loadMessages();
                        console.log('Chat messages loaded in modal');
                    } else {
                        console.error('loadMessages function not found on main page');
                    }
                }, 100);
            } else {
                console.error('Could not extract conversation ID from modal content');
            }
            
            chatModal.show();
        })
        .catch(error => {
            console.error('Error loading chat:', error);
            document.getElementById('chatModalBody').innerHTML = '<div class="alert alert-danger">Failed to load chat. Please try again.</div>';
            chatModal.show();
        });
}
</script>

<!-- Chat Modal -->
<div class="modal fade" id="chatModal" tabindex="-1" aria-labelledby="chatModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="chatModalLabel">Chat about {{ item.title }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="chatModalBody" style="height: 600px; overflow-y: auto;">
                <!-- Chat content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<!-- Unified Calendar Modal -->
<div class="modal fade" id="calendarModal" tabindex="-1" aria-labelledby="calendarModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="calendarModalLabel" style="line-height: 100%;">
                    <img src="/lendables/logo_checkdates_600.png" alt="Calendar" style="width: 84px; height: 84px; margin-right: 8px;">{{ item.name }}<br>Calendar & Availability
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <button onclick="changeModalMonth(-1)" class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <h6 id="modalCurrentMonth" class="mb-0">{{ "now"|date("F Y") }}</h6>
                    <button onclick="changeModalMonth(1)" class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead>
                            <tr class="text-center">
                                <th style="width: 14.28%;">Sun</th>
                                <th style="width: 14.28%;">Mon</th>
                                <th style="width: 14.28%;">Tue</th>
                                <th style="width: 14.28%;">Wed</th>
                                <th style="width: 14.28%;">Thu</th>
                                <th style="width: 14.28%;">Fri</th>
                                <th style="width: 14.28%;">Sat</th>
                            </tr>
                        </thead>
                        <tbody id="modalCalendarGrid">
                            <!-- Calendar days will be populated by JavaScript -->
                        </tbody>
                    </table>
                </div>
                
                <div class="mt-1">
                    <div class="d-flex flex-wrap gap-2 mb-2">
                        <span class="badge bg-success">Available</span>
                        <span class="badge bg-warning text-dark">Reserved</span>
                        <span class="badge bg-danger">On Loan</span>
                        <span class="badge" style="background-color: #8B0000; color: white;">Overdue</span>
                        <span class="badge" style="background-color: #0d6efd; color: white;">Selected</span>
                    </div>
                    {% if currentUser.id != item.owner %}
                    <div class="small text-muted mb-3">
                        <i class="fas fa-info-circle me-1"></i>
                        Click start date, then end date to select a range for borrowing
                    </div>
                    
                    <div id="modalSelectedDates" class="mt-2" style="display: none;">
                        <small class="text-muted">Selected dates: <span id="modalSelectedDatesList"></span></small>
                    </div>
                    
                    <div class="mt-3">
                        <label for="modalBorrowMessage" class="form-label">Message to {{ item.ownerShowName ?: item.ownerFirstName }} (optional)</label>
                        <textarea id="modalBorrowMessage" class="form-control" rows="2" placeholder="I would like to borrow this item..."></textarea>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <button onclick="clearModalSelection()" class="btn btn-outline-secondary btn-sm">Clear Selection</button>
                        <button onclick="submitModalRequest()" class="btn btn-success btn-sm" id="modalSubmitBtn" disabled>
                            {% if item.pricePerDay and item.pricePerDay > 0 %}Ask to Rent{% else %}Ask to Reserve{% endif %}
                        </button>
                    </div>
                    {% else %}
                    <div class="small text-muted mb-3">
                        <i class="fas fa-info-circle me-1"></i>
                        View your item's calendar availability and loan status
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
// Unified Calendar Modal System - Avoid conflicts by using unique namespace
(function() {
    'use strict';
    
    // Create unique namespace for calendar modal
    const CalendarModal = {
        currentDate: new Date(),
        selectedDatesList: [],
        calendarDataStore: {}
    };
    
    // Make openCalendarModal globally available
    window.openCalendarModal = function() {
        const modal = new bootstrap.Modal(document.getElementById('calendarModal'));
        modal.show();
        CalendarModal.loadData();
    };
    
    // Load calendar data for current month
    CalendarModal.loadData = async function() {
        try {
            const year = CalendarModal.currentDate.getFullYear();
            const month = CalendarModal.currentDate.getMonth() + 1;
            
            // Get user ID from URL or session - prioritize dashboard user
            const urlParams = new URLSearchParams(window.location.search);
            const dashboardUserId = document.referrer.match(/\/dashboard\/(\d+)/)?.[1];
            const userId = dashboardUserId || urlParams.get('user') || {{ currentUser.id }};
            
            const response = await fetch(`/api/items/{{ item.id }}/calendar/${year}/${month}?user=${userId}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            if (!data || typeof data !== 'object') {
                throw new Error('Invalid calendar data received');
            }
            
            CalendarModal.calendarDataStore = data;
            CalendarModal.renderCalendar();
        } catch (error) {
            console.error('=== CALENDAR ERROR DETAILS ===');
            console.error('Error loading calendar data:', error);
            console.error('Error name:', error.name);
            console.error('Error message:', error.message);
            console.error('Error stack:', error.stack);
            console.error('Response details:', error.message);
            console.error('Response status:', response ? response.status : 'no response');
            console.error('Response URL:', response ? response.url : 'no url');
            
            // Fallback: render calendar without data
            CalendarModal.calendarDataStore = { availability: [], loans: [], isOwner: false };
            CalendarModal.renderCalendar();
        }
    };
    
    // Render the calendar in the modal
    CalendarModal.renderCalendar = function() {
        const year = CalendarModal.currentDate.getFullYear();
        const month = CalendarModal.currentDate.getMonth();
    
    // Update month header
    const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
    
    const monthHeader = document.getElementById('modalCurrentMonth');
    if (!monthHeader) {
        console.error('Calendar modal month header element not found');
        return;
    }
    monthHeader.textContent = `${monthNames[month]} ${year}`;
    
    // Clear calendar grid
    const calendarGrid = document.getElementById('modalCalendarGrid');
    if (!calendarGrid) {
        console.error('Calendar modal grid element not found');
        return;
    }
    calendarGrid.innerHTML = '';
    
    // Calculate first day of month and number of days
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDayOfWeek = firstDay.getDay();
    
    let date = 1;
    
    // Create calendar rows
    for (let week = 0; week < 6; week++) {
        const row = document.createElement('tr');
        
        for (let day = 0; day < 7; day++) {
            const cell = document.createElement('td');
            cell.style.cssText = 'height: 40px; vertical-align: middle; text-align: center; cursor: pointer; position: relative;';
            
            if (week === 0 && day < startingDayOfWeek) {
                // Empty cells before month starts
                cell.innerHTML = '';
            } else if (date > daysInMonth) {
                // Empty cells after month ends
                cell.innerHTML = '';
            } else {
                const currentDate = new Date(year, month, date);
                const dateStr = currentDate.toISOString().split('T')[0];
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                
                cell.innerHTML = date;
                cell.setAttribute('data-date', dateStr);
                
                // Check availability status first (including for past dates)
                const availabilityData = CalendarModal.getDateAvailabilityWithDetails(dateStr);
                const availability = availabilityData.status;
                const isSelected = CalendarModal.selectedDatesList.includes(dateStr);
                
                if (isSelected) {
                    try {
                        cell.style.backgroundColor = '#0d6efd';
                        cell.style.color = 'white';
                        cell.setAttribute('data-bs-toggle', 'tooltip');
                        cell.setAttribute('data-bs-placement', 'top');
                        cell.setAttribute('data-bs-title', 'Selected for your request');
                    } catch (error) {
                        console.error('=== STYLE ERROR: Selected dates ===', error);
                        console.error('Cell element:', cell);
                    }
                } else if (availability === 'overdue') {
                    try {
                        console.log('=== OVERDUE CELL DEBUG ===');
                        console.log('Cell element:', cell);
                        console.log('CalendarModal.calendarDataStore:', CalendarModal.calendarDataStore);
                        console.log('isOwner:', CalendarModal.calendarDataStore ? CalendarModal.calendarDataStore.isOwner : 'no datastore');
                        console.log('borrowerName:', availabilityData.borrowerName);
                        
                        // Show overdue items in dark red regardless of past/future
                        cell.style.backgroundColor = '#8B0000';
                        cell.style.color = 'white';
                        
                        // Show appropriate tooltip/functionality for all users
                        cell.setAttribute('data-bs-toggle', 'tooltip');
                        cell.setAttribute('data-bs-placement', 'top');
                        
                        if (CalendarModal.calendarDataStore && CalendarModal.calendarDataStore.isOwner && availabilityData.borrowerName) {
                            console.log('=== OWNER TOOLTIP: Setting owner-specific tooltip ===');
                            console.log('=== AVAILABILITY DATA DEBUG ===', availabilityData);
                            console.log('=== BORROWER NAME DEBUG ===', availabilityData.borrowerName);
                            cell.setAttribute('data-bs-title', `Overdue - borrowed by ${availabilityData.borrowerName}. Click to send message.`);
                            cell.style.cursor = 'pointer';
                            cell.addEventListener('click', () => CalendarModal.openItemChat());
                        } else {
                            console.log('=== NON-OWNER TOOLTIP: Setting generic tooltip ===');
                            cell.setAttribute('data-bs-title', 'Overdue - unavailable');
                            cell.style.cursor = 'not-allowed';
                        }
                    } catch (error) {
                        console.error('=== STYLE ERROR: Overdue dates ===', error);
                        console.error('Cell element:', cell);
                        console.error('Availability data:', availabilityData);
                    }
                } else if (availability === 'on-loan') {
                    cell.style.backgroundColor = '#dc3545';
                    cell.style.color = 'white';
                    
                    // Show appropriate tooltip/functionality for all users
                    cell.setAttribute('data-bs-toggle', 'tooltip');
                    cell.setAttribute('data-bs-placement', 'top');
                    
                    if (CalendarModal.calendarDataStore && CalendarModal.calendarDataStore.isOwner && availabilityData.borrowerName) {
                        cell.setAttribute('data-bs-title', `On loan to ${availabilityData.borrowerName}. Click to send message.`);
                        cell.style.cursor = 'pointer';
                        cell.addEventListener('click', () => CalendarModal.openItemChat());
                    } else {
                        cell.setAttribute('data-bs-title', 'On loan - unavailable');
                        cell.style.cursor = 'not-allowed';
                    }
                } else if (availability === 'reserved') {
                    cell.style.backgroundColor = '#ffc107';
                    cell.style.color = '#000';
                    
                    // Show appropriate tooltip for all users
                    cell.setAttribute('data-bs-toggle', 'tooltip');
                    cell.setAttribute('data-bs-placement', 'top');
                    
                    if (CalendarModal.calendarDataStore && CalendarModal.calendarDataStore.isOwner && availabilityData.borrowerName) {
                        console.log('=== RESERVED TOOLTIP: Setting owner-specific tooltip ===');
                        console.log('=== RESERVED AVAILABILITY DATA DEBUG ===', availabilityData);
                        console.log('=== RESERVED BORROWER NAME DEBUG ===', availabilityData.borrowerName);
                        cell.setAttribute('data-bs-title', `Reserved by ${availabilityData.borrowerName}.\nClick to view your Item Chat.`);
                        cell.style.cursor = 'pointer';
                        cell.onclick = function() { 
                            const itemId = {{ item.id }};
                            window.location.href = `/item/${itemId}?chat=open`;
                        };
                    } else {
                        cell.setAttribute('data-bs-title', 'Reserved');
                    }
                    cell.style.cursor = 'not-allowed';
                } else if (currentDate <= today) {
                    // Show past dates and today as transparent unless they have special status
                    cell.style.backgroundColor = 'transparent';
                    cell.style.color = '#ccc';
                    cell.style.cursor = 'not-allowed';
                } else {
                    cell.style.backgroundColor = '#28a745';
                    cell.style.color = 'white';
                    cell.setAttribute('data-bs-toggle', 'tooltip');
                    cell.setAttribute('data-bs-placement', 'top');
                    cell.setAttribute('data-bs-title', 'Available');
                    cell.addEventListener('click', () => CalendarModal.selectDate(dateStr));
                }
                
                date++;
            }
            
            row.appendChild(cell);
        }
        
        calendarGrid.appendChild(row);
        
        if (date > daysInMonth) break;
    }
    
        CalendarModal.updateSelectedDatesDisplay();
        
        // Initialize Bootstrap tooltips for calendar cells after a short delay
        setTimeout(() => {
            // Dispose of any existing tooltips first
            const existingTooltips = document.querySelectorAll('#modalCalendarGrid [data-bs-toggle="tooltip"]');
            existingTooltips.forEach(el => {
                const existingTooltip = bootstrap.Tooltip.getInstance(el);
                if (existingTooltip) {
                    existingTooltip.dispose();
                }
            });
            
            // Initialize new tooltips
            const tooltipTriggerList = document.querySelectorAll('#modalCalendarGrid [data-bs-toggle="tooltip"]');
            console.log(`Initializing ${tooltipTriggerList.length} calendar tooltips`);
            
            if (tooltipTriggerList.length > 0 && typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
                const tooltipList = [...tooltipTriggerList].map((tooltipTriggerEl, index) => {
                    try {
                        console.log(`=== TOOLTIP DEBUG: Initializing tooltip ${index + 1} ===`);
                        console.log('Element:', tooltipTriggerEl);
                        console.log('Element classList:', tooltipTriggerEl.classList.toString());
                        console.log('Element title:', tooltipTriggerEl.getAttribute('data-bs-title'));
                        
                        const tooltip = new bootstrap.Tooltip(tooltipTriggerEl, {
                            delay: { show: 300, hide: 100 },
                            placement: 'top'
                        });
                        
                        console.log(`=== TOOLTIP DEBUG: Successfully created tooltip ${index + 1} ===`);
                        return tooltip;
                    } catch (error) {
                        console.error(`=== TOOLTIP DEBUG: Error initializing tooltip ${index + 1}:`, error);
                        console.error('Element that failed:', tooltipTriggerEl);
                        return null;
                    }
                });
                console.log(`Successfully initialized ${tooltipList.filter(t => t !== null).length} tooltips`);
            } else {
                console.error('Bootstrap or Tooltip not available, or no tooltip elements found');
            }
        }, 200);
    };

    // Get availability status for a specific date
    CalendarModal.getDateAvailability = function(dateStr) {
        const result = CalendarModal.getDateAvailabilityWithDetails(dateStr);
        return result.status;
    };

    // Get detailed availability status with borrower information
    CalendarModal.getDateAvailabilityWithDetails = function(dateStr) {
        if (!CalendarModal.calendarDataStore) return { status: 'available', borrowerName: null };
        
        // Check for active loans first (highest priority) - these have borrower names
        if (CalendarModal.calendarDataStore.loans) {
            for (let loan of CalendarModal.calendarDataStore.loans) {
                const startDate = new Date((loan.borrowedDate || loan.startDate).split('T')[0] + 'T12:00:00.000Z');
                const endDate = new Date((loan.expectedReturnDate || loan.endDate || loan.borrowedDate || loan.startDate).split('T')[0] + 'T12:00:00.000Z');
                const checkDate = new Date(dateStr + 'T12:00:00.000Z');
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                
                if (checkDate >= startDate && checkDate <= endDate) {
                    console.log('=== LOAN DEBUG: Using loan data with borrower ===', loan.borrowerName || loan.displayName);
                    const borrowerName = loan.borrowerName || loan.displayName || 'Unknown User';
                    
                    if (loan.status === 'overdue') {
                        return { status: 'overdue', borrowerName: borrowerName };
                    } else if (loan.status === 'active' || (loan.status === 'approved' && new Date(loan.expectedReturnDate || loan.endDate) < new Date())) {
                        return { status: 'on-loan', borrowerName: borrowerName };
                    } else if (loan.status === 'reserved' || loan.status === 'approved') {
                        return { status: 'reserved', borrowerName: borrowerName };
                    }
                }
                
                // Check if this is an overdue loan that extends beyond expected return date
                if (loan.status === 'overdue' && checkDate >= startDate && checkDate <= today) {
                    const borrowerName = loan.borrowerName || loan.displayName || 'Unknown User';
                    return { status: 'overdue', borrowerName: borrowerName };
                }
            }
        }
        
        // Check availability array structure
        if (CalendarModal.calendarDataStore.availability && Array.isArray(CalendarModal.calendarDataStore.availability)) {
            for (let avail of CalendarModal.calendarDataStore.availability) {
                // Parse dates to avoid timezone conversion issues
                const startDate = new Date(avail.start_date.split('T')[0] + 'T12:00:00.000Z');
                const endDate = new Date((avail.end_date || avail.start_date).split('T')[0] + 'T12:00:00.000Z');
                const checkDate = new Date(dateStr + 'T12:00:00.000Z');
                
                if (checkDate >= startDate && checkDate <= endDate) {
                    if (avail.status === 'approved') {
                        console.log('=== AVAILABILITY ARRAY DEBUG: Processing avail ===', avail);
                        console.log('=== AVAILABILITY ARRAY DEBUG: borrowerName field ===', avail.borrowerName);
                        const borrowerName = avail.borrowerName || 'Unknown User';
                        return { status: 'reserved', borrowerName: borrowerName };
                    }
                }
            }
        }
        
        return { status: 'available', borrowerName: null };
    };

    // Open item chat when clicking on loan dates
    CalendarModal.openItemChat = function() {
        // Close the calendar modal first
        const calendarModal = bootstrap.Modal.getInstance(document.getElementById('calendarModal'));
        if (calendarModal) {
            calendarModal.hide();
        }
        
        // Open the chat panel using the existing function
        if (typeof toggleChatPanel === 'function') {
            toggleChatPanel();
        } else {
            // Fallback: scroll to existing chat section or navigate to item detail with chat open
            const chatSection = document.getElementById('chatSection');
            if (chatSection) {
                chatSection.scrollIntoView({ behavior: 'smooth' });
            } else {
                // Navigate to item detail page with chat parameter
                const itemId = {{ item.id }};
                window.location.href = `/item/${itemId}?chat=open`;
            }
        }
    };

    // Select/deselect a date
    CalendarModal.selectDate = function(dateStr) {
        const availability = CalendarModal.getDateAvailability(dateStr);
        if (availability !== 'available') return;
        
        if (CalendarModal.selectedDatesList.length === 0) {
            // First date selection
            CalendarModal.selectedDatesList.push(dateStr);
        } else if (CalendarModal.selectedDatesList.length === 1) {
            // Second date selection - create range
            const firstDate = new Date(CalendarModal.selectedDatesList[0]);
            const secondDate = new Date(dateStr);
            
            if (secondDate < firstDate) {
                // If second date is before first, swap them
                CalendarModal.selectedDatesList = [dateStr, CalendarModal.selectedDatesList[0]];
            } else {
                CalendarModal.selectedDatesList.push(dateStr);
            }
            
            // Fill in the range
            const startDate = new Date(Math.min(new Date(CalendarModal.selectedDatesList[0]), new Date(CalendarModal.selectedDatesList[1])));
            const endDate = new Date(Math.max(new Date(CalendarModal.selectedDatesList[0]), new Date(CalendarModal.selectedDatesList[1])));
            CalendarModal.selectedDatesList = [];
            
            for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
                const checkDateStr = d.toISOString().split('T')[0];
                if (CalendarModal.getDateAvailability(checkDateStr) === 'available') {
                    CalendarModal.selectedDatesList.push(checkDateStr);
                }
            }
        } else {
            // Clear previous selection and start new
            CalendarModal.selectedDatesList = [dateStr];
        }
        
        CalendarModal.renderCalendar();
    };

    // Change month in modal  
    CalendarModal.changeMonth = function(direction) {
        CalendarModal.currentDate.setMonth(CalendarModal.currentDate.getMonth() + direction);
        CalendarModal.loadData();
    };

    // Clear date selection
    CalendarModal.clearSelection = function() {
        CalendarModal.selectedDatesList = [];
        CalendarModal.renderCalendar();
    };

    // Update selected dates display
    CalendarModal.updateSelectedDatesDisplay = function() {
        const selectedDatesDiv = document.getElementById('modalSelectedDates');
        const selectedDatesList = document.getElementById('modalSelectedDatesList');
        const submitBtn = document.getElementById('modalSubmitBtn');
        
        // Add null checks to prevent style errors
        if (!selectedDatesDiv || !selectedDatesList || !submitBtn) {
            console.log('Some calendar modal elements not found - skipping display update');
            return;
        }
        
        if (CalendarModal.selectedDatesList.length > 0) {
            selectedDatesDiv.style.display = 'block';
            selectedDatesList.textContent = CalendarModal.selectedDatesList.length > 1 
                ? `${CalendarModal.selectedDatesList[0]} to ${CalendarModal.selectedDatesList[CalendarModal.selectedDatesList.length - 1]} (${CalendarModal.selectedDatesList.length} days)`
                : CalendarModal.selectedDatesList[0];
            submitBtn.disabled = false;
        } else {
            selectedDatesDiv.style.display = 'none';
            submitBtn.disabled = true;
        }
    };

    // Submit borrow request with selected dates
    CalendarModal.submitRequest = async function() {
        if (CalendarModal.selectedDatesList.length === 0) return;
        
        // Check if this is a rental item
        const itemPricePerDay = {{ item.pricePerDay ?? 0 }};
        
        if (itemPricePerDay > 0) {
            // For rental items, show rental cost calculation modal first
            CalendarModal.showRentalCostModal();
        } else {
            // For regular borrow items, proceed directly
            CalendarModal.submitFinalRequest();
        }
    };

    // Show rental cost calculation modal
    CalendarModal.showRentalCostModal = function() {
        const numDays = CalendarModal.selectedDatesList.length;
        const dailyRate = {{ item.pricePerDay ?? 0 }};
        const totalCost = numDays * dailyRate;
        
        const startDate = CalendarModal.selectedDatesList[0];
        const endDate = CalendarModal.selectedDatesList[CalendarModal.selectedDatesList.length - 1];
        
        // Update rental cost modal content
        document.getElementById('rentalItemName').textContent = '{{ item.name }}';
        document.getElementById('rentalStartDate').textContent = parseUTCDate(startDate).toLocaleDateString();
        document.getElementById('rentalEndDate').textContent = parseUTCDate(endDate).toLocaleDateString();
        document.getElementById('rentalNumDays').textContent = numDays;
        document.getElementById('rentalDailyRate').textContent = '$' + dailyRate.toFixed(2);
        document.getElementById('rentalTotalCost').textContent = '$' + totalCost.toFixed(2);
        
        // Carry over message from calendar modal to rental modal
        const calendarMessage = document.getElementById('modalBorrowMessage')?.value || '';
        document.getElementById('rentalMessage').value = calendarMessage;
        
        // Hide calendar modal and show rental cost modal
        const calendarModal = bootstrap.Modal.getInstance(document.getElementById('calendarModal'));
        calendarModal.hide();
        
        const rentalModal = new bootstrap.Modal(document.getElementById('rentalCostModal'));
        rentalModal.show();
    };

    // Submit final rental request
    CalendarModal.submitFinalRequest = async function() {
        if (CalendarModal.selectedDatesList.length === 0) return;
        
        const formData = {
            itemId: {{ item.id }},
            startDate: CalendarModal.selectedDatesList[0],
            endDate: CalendarModal.selectedDatesList[CalendarModal.selectedDatesList.length - 1],
            message: document.getElementById('modalBorrowMessage')?.value || document.getElementById('rentalMessage')?.value || 'I would like to borrow this item.'
        };
        
        try {
            const response = await fetch('/api/borrow-requests', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                // Close any open modals
                const calendarModal = bootstrap.Modal.getInstance(document.getElementById('calendarModal'));
                if (calendarModal) calendarModal.hide();
                
                const rentalModal = bootstrap.Modal.getInstance(document.getElementById('rentalCostModal'));
                if (rentalModal) rentalModal.hide();
                
                // Show success alert
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-success alert-dismissible fade show';
                alertDiv.innerHTML = `
                    <strong>Request sent!</strong> Your ${{{ item.pricePerDay ?? 0 }} > 0 ? 'rental' : 'borrow'} request has been submitted.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.querySelector('.container-fluid').insertBefore(alertDiv, document.querySelector('.container-fluid').firstChild);
                
                // Refresh page after 2 seconds
                setTimeout(() => window.location.reload(), 2000);
            } else {
                LocalLendables.showErrorToast('Request Failed', result.error || 'Unknown error occurred while submitting your request.');
            }
        } catch (error) {
            console.error('Error submitting borrow request:', error);
            LocalLendables.showErrorToast('Request Error', 'Error submitting request. Please try again.');
        }
    };

    // Make functions globally accessible for HTML onclick handlers
    window.changeModalMonth = CalendarModal.changeMonth;
    window.clearModalSelection = CalendarModal.clearSelection;
    window.submitModalRequest = CalendarModal.submitRequest;
    window.submitFinalRentalRequest = CalendarModal.submitFinalRequest;

})();

// Global function for rental submission with empty message confirmation
function handleRentalSubmission() {
    const rentalMessage = document.getElementById('rentalMessage')?.value || '';
    
    if (!rentalMessage.trim()) {
        // If no message, ask for confirmation
        if (!confirm('Send with no message? Y/N')) {
            return; // User cancelled
        }
    }
    
    // Proceed with submission - call the CalendarModal function
    window.submitFinalRentalRequest();
}

// Push Return Modal functionality
function openPushReturnModal() {
    // Create and show the modal
    const modal = new bootstrap.Modal(document.getElementById('pushReturnModal'));
    modal.show();
}

function toggleConcernsMessage() {
    const goodConditionCheckbox = document.getElementById('pushReturnConfirm');
    const concernsCheckbox = document.getElementById('borrowerConcerns');
    const messageBox = document.getElementById('concernsMessageBox');
    
    // Radio button behavior - only one can be checked
    if (concernsCheckbox.checked) {
        goodConditionCheckbox.checked = false;
        messageBox.style.display = 'block';
    } else {
        messageBox.style.display = 'none';
        document.getElementById('concernsMessage').value = '';
    }
    updateReturnButton();
}

function toggleGoodCondition() {
    const goodConditionCheckbox = document.getElementById('pushReturnConfirm');
    const concernsCheckbox = document.getElementById('borrowerConcerns');
    const messageBox = document.getElementById('concernsMessageBox');
    
    // Radio button behavior - only one can be checked
    if (goodConditionCheckbox.checked) {
        concernsCheckbox.checked = false;
        messageBox.style.display = 'none';
        document.getElementById('concernsMessage').value = '';
    }
    updateReturnButton();
}

function updateReturnButton() {
    const goodConditionCheckbox = document.getElementById('pushReturnConfirm');
    const concernsCheckbox = document.getElementById('borrowerConcerns');
    const button = document.querySelector('#pushReturnModal .btn-success');
    
    if (concernsCheckbox.checked) {
        button.innerHTML = '<i class="fas fa-check me-1"></i>Item Returned<br>but with concerns';
    } else {
        button.innerHTML = '<i class="fas fa-check me-1"></i>Confirm Return';
    }
}

function submitPushReturn() {
    const goodCondition = document.getElementById('pushReturnConfirm').checked;
    const hasConcerns = document.getElementById('borrowerConcerns').checked;
    const concernsMessage = document.getElementById('concernsMessage').value;
    
    if (!goodCondition && !hasConcerns) {
        LocalLendables.showErrorToast('Selection Required', 'Please confirm the item condition by selecting one option.');
        return;
    }
    
    if (hasConcerns && !concernsMessage.trim()) {
        LocalLendables.showErrorToast('Message Required', 'Please provide details about your concerns.');
        return;
    }
    
    // Get loan ID from loan status
    {% if loanStatus and loanStatus.isOnLoan %}
    const loanId = {{ loanStatus.loanId ?? 'null' }};
    {% else %}
    const loanId = null;
    {% endif %}
    
    if (!loanId) {
        LocalLendables.showErrorToast('Loan Not Found', 'Unable to find loan information. Please try again or contact support.');
        return;
    }
    
    // Submit push return request
    fetch(`/api/loans/${loanId}/push-return`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            confirmed: true,
            hasConcerns: hasConcerns,
            concernsMessage: hasConcerns ? concernsMessage : null
        })
    })
    .then(response => response.json())
    .then(result => {
        console.log('Push return result:', result);
        if (result.success) {
            // Close modal first
            const modal = bootstrap.Modal.getInstance(document.getElementById('pushReturnModal'));
            if (modal) modal.hide();
            
            // Show beautiful success toast
            LocalLendables.showSuccessToast(
                'Return Confirmed!',
                'The item has been marked as returned successfully. The borrower will be notified.'
            );
            
            // Refresh page to show updated status after a short delay
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            LocalLendables.showErrorToast(
                'Return Error',
                result.error || 'Unknown error occurred while confirming return.'
            );
        }
    })
    .catch(error => {
        console.error('Error submitting push return:', error);
        LocalLendables.showErrorToast(
            'Connection Error',
            'Unable to confirm return. Please check your connection and try again.'
        );
    });
}

// Toggle favorite function
function toggleFavorite(itemId, button, heartIcon) {
    const userId = {{ currentUser.id }};
    
    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.title = 'Remove from favorites';
            } else {
                heartIcon.style.color = '#ccc'; // Gray when not favorited
                button.title = 'Add to favorites';
            }
        } else {
            console.error('Failed to toggle favorite:', data.error);
        }
    })
    .catch(error => {
        console.error('Error toggling favorite:', error);
    });
}

// RESPONSIVE LAYOUT CONTROLLER - JavaScript-based solution
function setupResponsiveLayout() {
    const mobileLayout = document.querySelector('.mobile-header-layout');
    const desktopLayout = document.querySelector('.desktop-header-layout');
    
    function updateLayout() {
        const isMobile = window.innerWidth <= 768;
        
        if (isMobile) {
            // Mobile: Show mobile layout, hide desktop
            if (mobileLayout) mobileLayout.style.display = 'flex';
            if (desktopLayout) desktopLayout.style.display = 'none';
            
            // Force mobile image size with JavaScript
            const mobileImage = mobileLayout.querySelector('.mobile-item-image');
            if (mobileImage) {
                mobileImage.style.width = '80px';
                mobileImage.style.maxWidth = '80px';
                mobileImage.style.minWidth = '80px';
                mobileImage.style.height = 'auto';
                console.log('Mobile image forced to 80px width');
            }
        } else {
            // Desktop: Show desktop layout, hide mobile
            if (mobileLayout) mobileLayout.style.display = 'none';
            if (desktopLayout) desktopLayout.style.display = 'flex';
        }
        
        console.log(`Layout updated: ${isMobile ? 'Mobile' : 'Desktop'} (width: ${window.innerWidth}px)`);
    }
    
    // Initialize layout on page load
    updateLayout();
    
    // Update layout on window resize
    window.addEventListener('resize', updateLayout);
    
    console.log('Responsive layout controller initialized');
}

// Initialize responsive layout when page loads
document.addEventListener('DOMContentLoaded', function() {
    setupResponsiveLayout();
});

// Image modal functionality
function openImageModal(imageSrc, itemName) {
    // Create modal HTML
    const modalHTML = `
        <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="imageModalLabel">${itemName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body text-center">
                        <img src="${imageSrc}" alt="${itemName}" class="img-fluid" style="max-height: 70vh;">
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('imageModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add new modal to DOM
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
    
    // Clean up when modal is hidden
    document.getElementById('imageModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

function deleteAudioMessage(messageId) {
    if (!confirm('Are you sure you want to delete this audio message?')) {
        return;
    }
    
    fetch(`/api/chat/message/${messageId}/delete`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadChatMessages(); // Reload messages to reflect deletion
        } else {
            alert('Failed to delete message: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error deleting message:', error);
        alert('Error deleting message');
    });
}

</script>

<!-- Push Return Modal -->
<div class="modal fade" id="pushReturnModal" tabindex="-1" aria-labelledby="pushReturnModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="pushReturnModalLabel">
                    <i class="fas fa-undo me-2"></i>Confirm Item Return
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info small" style="line-height: 1.0;">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Item Now Back?</strong> Use this to mark your item as returned when you have physically received it back from the borrower.
                </div>
                
                {% if loanStatus and loanStatus.isOnLoan %}
                <div class="mb-3">
                    <h6>Item Details:</h6>
                    <p><strong>{{ item.title }}</strong></p>
                    <p>Currently borrowed by: <strong>{{ loanStatus.borrowerName ?: 'Unknown' }}</strong></p>
                    {% if loanStatus.endDate %}
                    <p>Expected return: <strong>{{ loanStatus.endDate|date('M j, Y') }}</strong></p>
                    {% endif %}
                </div>
                {% endif %}
                
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="pushReturnConfirm" onchange="toggleGoodCondition()">
                    <label class="form-check-label" for="pushReturnConfirm">
                        <strong>I confirm that I have received this item back in good condition.</strong>
                    </label>
                </div>
                
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" id="borrowerConcerns" onchange="toggleConcernsMessage()">
                    <label class="form-check-label" for="borrowerConcerns">
                        <strong>I have concerns about the condition of this Item</strong>
                    </label>
                </div>
                
                <div id="concernsMessageBox" class="mt-3" style="display: none;">
                    <div class="mb-2">
                        <small class="text-muted">Message will be sent to the Borrower</small>
                    </div>
                    <textarea class="form-control" id="concernsMessage" rows="3" placeholder="Describe your concerns about the item's condition..."></textarea>
                </div>
                
                <div class="mt-3">
                    <small class="text-muted">
                        <i class="fas fa-bell me-1"></i>
                        The borrower will be notified that the return has been confirmed.
                    </small>
                </div>
            </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="submitPushReturn()">
                    <i class="fas fa-check me-1"></i>Confirm Return
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}