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

{% block title %}Our Lendables Dashboard - Local Lendables{% endblock %}

{% block content %}
<!-- Welcome Alert -->
<script>
    if (typeof document !== 'undefined' && document) {
        document.addEventListener("DOMContentLoaded", function () {
            if (typeof Swal !== 'undefined') {
                // Check if this user has already seen the welcome popup
                const currentUserId = '{{ user.id }}';
                const welcomeShownKey = 'welcomeShown_' + currentUserId;
                const hasSeenWelcome = localStorage.getItem(welcomeShownKey);
                
                if (!hasSeenWelcome) {
                    Swal.fire({
                        title: "Welcome to our Local Lendables Demo",
                        text: "You are now logged in as {% if user.showName %}{{ user.showName }}{% else %}{{ user.firstName }} {{ user.lastName }}{% endif %}!",
                        icon: 'success',
                        confirmButtonText: 'Start Exploring',
                        confirmButtonColor: '#28a745'
                    }).then(function() {
                        // Mark this user as having seen the welcome popup
                        localStorage.setItem(welcomeShownKey, 'true');
                    });
                }
            }
        });
    }

    // Logout function with browser history prevention
    function performLogout() {
        Swal.fire({
            title: 'Logout Confirmation',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Logout',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Clear browser history and redirect to demo
                window.location.replace('/logout');
            }
        });
    }

    // Messages modal functionality
    function showMessagesModal() {
        const modal = new bootstrap.Modal(document.getElementById('messagesModal'));
        modal.show();
        
        // Load unread messages
        fetchUnreadMessages();
    }
    
    async function fetchUnreadMessages() {
        try {
            const response = await fetch('/api/unread-messages/{{ user.id }}');
            const data = await response.json();
            
            const modalBody = document.getElementById('messagesModalBody');
            
            if (data.messages && data.messages.length > 0) {
                modalBody.innerHTML = data.messages.map((msg, index) => {
                    if (msg.isSystemNotification) {
                        // Special card design for system notifications (overdue messages, agreement ready)
                        const isOverdue = msg.notificationType && msg.notificationType.includes('overdue');
                        const isAgreementReady = msg.type === 'agreement_ready';
                        const cardBorderClass = isOverdue ? 'border-danger' : isAgreementReady ? 'border-success' : 'border-warning';
                        const badgeClass = isOverdue ? 'bg-danger' : isAgreementReady ? 'bg-success' : 'bg-warning';
                        const badgeText = isOverdue ? 'OVERDUE' : isAgreementReady ? 'AGREEMENT READY' : 'REMINDER';
                        
                        // Determine click behavior based on notification type
                        const isOverdueReturn = msg.type && (msg.type.startsWith('return_') || msg.type.includes('overdue')) || (msg.preview && msg.preview.toLowerCase().includes('overdue'));
                        const clickUrl = isOverdueReturn ? `/return/${msg.item_id}?userId={{ user.id }}` : 
                                        isAgreementReady ? `/agreement/${msg.agreementId || msg.relatedId}` : 
                                        `/item/${msg.item_id}?calendar=open`;
                        const clickTitle = isOverdueReturn ? "Click to return this item" : 
                                         isAgreementReady ? "Click to sign loan agreement" : 
                                         "Click to view item details";
                        
                        return `
                            <div class="card mb-2 ${cardBorderClass} system-notification-card" id="message-card-${index}" onclick="window.location.href='${clickUrl}'" style="cursor: pointer;" title="${clickTitle}">
                                <div class="card-body p-3">
                                    <div class="d-flex align-items-start">
                                        <div class="me-3 d-flex flex-column align-items-center">
                                            <i class="fas ${isAgreementReady ? 'fa-file-signature text-success' : 'fa-clock ' + (isOverdue ? 'text-danger' : 'text-warning')} mb-2" style="font-size: 2rem;"></i>
                                            ${msg.item_thumbnail 
                                                ? `<img src="/lendable_items/${msg.item_thumbnail}" alt="${msg.item_name}" class="rounded" style="width: 80px; height: 60px; object-fit: cover;">`
                                                : `<div class="bg-light border rounded d-flex align-items-center justify-content-center" style="width: 80px; height: 60px; font-size: 10px; color: #666;">No Image</div>`
                                            }
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="d-flex justify-content-between align-items-start mb-1">
                                                <h6 class="card-title mb-0">${msg.item_name}</h6>
                                                <div class="d-flex align-items-center gap-2">
                                                    <span class="badge ${badgeClass} text-white">${badgeText}</span>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="event.stopPropagation(); markMessageAsRead('${msg.messageId}', ${msg.isSystemNotification})" aria-label="Mark as read" title="Mark as read - won't show again">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            ${msg.dueDate ? `<p class="text-muted small mb-1"><i class="fas fa-calendar me-1"></i>Due: ${msg.dueDate}</p>` : ''}
                                            ${msg.owner_name ? `<p class="text-muted small mb-1"><i class="fas fa-user me-1"></i>Owner: ${msg.owner_name}</p>` : ''}
                                            <p class="mb-2 ${isOverdue ? 'text-danger fw-bold' : isAgreementReady ? 'text-success fw-semibold' : 'text-warning fw-semibold'}">${msg.preview}</p>
                                            <small class="text-muted">
                                                <i class="fas fa-building me-1"></i>LocalLendables System • ${new Date(msg.created_at).toLocaleString()}
                                            </small>
                                            <div class="mt-2">
                                                ${isOverdue && msg.type && msg.type.startsWith('return_') ? 
                                                    `<a href="/return/${msg.item_id}?userId=${msg.userId || '{{ user.id }}'}" class="btn btn-danger btn-sm me-2" onclick="event.stopPropagation()">
                                                        <i class="fas fa-undo me-1"></i>Return This Item
                                                    </a>` : 
                                                    isOverdue && msg.type && msg.type.startsWith('owner_') && msg.preview && msg.preview.includes('Shall we send a reminder?') ?
                                                    `<button class="btn btn-primary btn-sm me-2" onclick="event.stopPropagation(); openReminderForm('${msg.messageId}', '${msg.item_id}', '${msg.preview}')">
                                                        <i class="fas fa-paper-plane me-1"></i>Send Reminder
                                                    </button>
                                                    <small class="text-muted d-block mt-1"><i class="fas fa-hand-pointer me-1"></i>Click to send reminder</small>` :
                                                    isOverdue && msg.type && msg.type.startsWith('owner_') ?
                                                    `<a href="/item/${msg.item_id}" class="btn btn-warning btn-sm me-2" onclick="event.stopPropagation()">
                                                        <i class="fas fa-envelope me-1"></i>Contact Borrower
                                                    </a>` :
                                                    isAgreementReady ?
                                                    `<a href="/agreement/${msg.agreementId || msg.relatedId}" class="btn btn-success btn-sm me-2" onclick="event.stopPropagation()">
                                                        <i class="fas fa-file-signature me-1"></i>Sign Agreement
                                                    </a>
                                                    <small class="text-muted d-block mt-1"><i class="fas fa-hand-pointer me-1"></i>Click to sign loan agreement</small>` :
                                                    `<small class="text-muted"><i class="fas fa-mouse-pointer me-1"></i>Click to view item details</small>`
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    } else {
                        // Regular chat message format - check if it's a borrow request
                        const isBorrowRequest = msg.preview && msg.preview.includes('Borrow request:');
                        const cardClickUrl = isBorrowRequest ? `/borrow-response/${msg.item_id}?messageId=${msg.messageId}` : `/item/${msg.item_id}`;
                        const cardOnClick = `onclick="window.location.href='${cardClickUrl}'" style="cursor: pointer;"`;
                        const cardTitle = isBorrowRequest ? 'Click entire card to respond to borrow request' : 'Click entire card to view item details';
                        
                        return `
                            <div class="card mb-2" id="message-card-${msg.messageId}" ${cardOnClick} title="${cardTitle}">
                                <div class="card-body p-3">
                                    <div class="d-flex align-items-start">
                                        <div class="me-3 d-flex flex-column align-items-center">
                                            ${msg.sender_avatar 
                                                ? `<img src="/ll_images/${msg.sender_avatar}" alt="${msg.sender_name}" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;" onerror="this.src='/avatars/default.svg'">`
                                                : `<div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px; font-size: 14px;">${(msg.sender_name || 'U').charAt(0).toUpperCase()}</div>`
                                            }
                                            ${msg.item_thumbnail 
                                                ? `<img src="/lendable_items/${msg.item_thumbnail}" alt="${msg.item_name}" class="mt-2 rounded" style="width: 100px; height: auto; object-fit: cover;">`
                                                : `<div class="mt-2 bg-light border rounded d-flex align-items-center justify-content-center" style="width: 100px; height: 60px; font-size: 10px; color: #666;">No Image</div>`
                                            }
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="d-flex justify-content-between align-items-start mb-1">
                                                <h6 class="card-title mb-0">${msg.item_name || 'Chat'}</h6>
                                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="event.stopPropagation(); markMessageAsRead('${msg.messageId}', false)" aria-label="Mark as read" title="Mark as read - won't show again">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                            <p class="text-muted small mb-1">From: ${msg.sender_name}</p>
                                            ${msg.messageType === 'audio' && msg.audio_path ? 
                                                `<div class="mb-2">
                                                    <audio controls style="width: 100%; max-width: 300px;">
                                                        <source src="${msg.audio_path}" type="audio/webm">
                                                        <source src="${msg.audio_path}" type="audio/wav">
                                                        Your browser does not support the audio element.
                                                    </audio>
                                                </div>` : 
                                                `<p class="mb-1">${msg.preview}</p>`
                                            }
                                            <small class="text-muted">${new Date(msg.created_at).toLocaleString()}</small>
                                        </div>
                                    </div>
                                    ${isBorrowRequest ? 
                                        `<div class="mt-2">
                                            <span class="badge bg-primary">Borrow Request - Click anywhere on this card to respond</span>
                                        </div>` :
                                        `<div class="mt-2">
                                            ${msg.type === 'agreement_ready' ? 
                                                `<a href="/agreement/${msg.agreementId || msg.relatedId}" class="btn btn-success btn-sm">
                                                    <i class="fas fa-file-signature me-1"></i>Sign Agreement
                                                </a>` :
                                                `<a href="/item/${msg.item_id}" class="btn btn-primary btn-sm" onclick="sessionStorage.setItem('openChatOnLoad', 'true'); return true;">Reply to ${msg.sender_name}</a>`
                                            }
                                        </div>`
                                    }
                                </div>
                            </div>
                        `;
                    }
                }).join('');
            } else {
                modalBody.innerHTML = '<p class="text-center text-muted">No unread messages</p>';
            }
        } catch (error) {
            console.error('Error fetching messages:', error);
            document.getElementById('messagesModalBody').innerHTML = '<p class="text-center text-danger">Error loading messages</p>';
        }
    }

    // Function to dismiss individual message cards
    function dismissMessage(cardIndex) {
        const messageCard = document.getElementById(`message-card-${cardIndex}`);
        if (messageCard) {
            messageCard.style.transition = 'opacity 0.3s ease';
            messageCard.style.opacity = '0';
            setTimeout(() => {
                messageCard.remove();
                
                // Check if there are any remaining message cards
                const remainingCards = document.querySelectorAll('[id^="message-card-"]');
                if (remainingCards.length === 0) {
                    document.getElementById('messagesModalBody').innerHTML = '<p class="text-center text-muted">No unread messages</p>';
                }
            }, 300);
        }
    }
</script>





<!-- Main Content -->
<main class="content-wrapper">
    <section class="container pt-1 mt-1">
        <!-- Custom Dashboard Header with Messages -->
        <!-- Desktop Layout -->
        <div class="d-flex align-items-center mb-2 d-none d-md-flex">
            <h4 class="mb-0 me-3">Dashboard</h4>
            {% if (hasUnreadChats and unreadChatCount > 0) or systemNotification %}
            <button type="button" class="btn btn-sm btn-danger fw-bold" style="background-color: #dc3545; border-color: #dc3545;" onclick="showMessagesModal()">
                New Messages and Notifications!
            </button>
            {% endif %}
        </div>
        
        <!-- Mobile Layout -->
        <div class="d-block d-md-none mb-2">
            <div class="d-flex align-items-center">
                <h4 class="mb-0 me-2">Dashboard</h4>
                {% if (hasUnreadChats and unreadChatCount > 0) or systemNotification %}
                <button type="button" class="btn btn-sm btn-danger fw-bold" style="background-color: #dc3545; border-color: #dc3545; font-size: 0.8rem; padding: 4px 8px;" onclick="showMessagesModal()">
                    New Messages and Notifications!
                </button>
                {% endif %}
            </div>
        </div>
        
        <!-- Notification Area -->
        <div id="notification-area" class="mb-3">
            {% if systemNotification %}
            <div id="blueNotificationBar" class="notification-bar-permanent" 
                 {% if systemNotification.message and 'Shall we send a reminder?' in systemNotification.message %}
                 onclick="openReminderForm({{ systemNotification.id }}, {{ systemNotification.itemId }}, '{{ systemNotification.message|e('js') }}')" 
                 style="cursor: pointer !important; background-color: #cfe2ff !important; border: 1px solid #b6d4fe !important; color: #084298 !important; padding: 12px 16px !important; border-radius: 4px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; margin-bottom: 16px !important; position: relative !important; z-index: 100 !important; width: 100% !important; min-height: 50px !important;"
                 title="Click to send reminder"
                 {% elseif systemNotification.type == 'agreement_ready' and systemNotification.relatedId %}
                 onclick="window.location.href='/agreement/{{ systemNotification.relatedId }}'" 
                 style="cursor: pointer !important; background-color: #d1e7dd !important; border: 1px solid #badbcc !important; color: #0f5132 !important; padding: 12px 16px !important; border-radius: 4px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; margin-bottom: 16px !important; position: relative !important; z-index: 100 !important; width: 100% !important; min-height: 50px !important;"
                 title="Click to sign loan agreement"
                 {% elseif systemNotification.itemId %}onclick="window.location.href='{% if systemNotification.type and (systemNotification.type starts with 'return_' or systemNotification.type starts with 'owner_overdue' or 'overdue' in systemNotification.message|lower) %}/return/{{ systemNotification.itemId }}?userId={{ user.id }}{% else %}/item/{{ systemNotification.itemId }}?calendar=open{% endif %}'" style="cursor: pointer !important; background-color: #cfe2ff !important; border: 1px solid #b6d4fe !important; color: #084298 !important; padding: 12px 16px !important; border-radius: 4px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; margin-bottom: 16px !important; position: relative !important; z-index: 100 !important; width: 100% !important; min-height: 50px !important;" title="{% if systemNotification.type and (systemNotification.type starts with 'return_' or systemNotification.type starts with 'owner_overdue' or 'overdue' in systemNotification.message|lower) %}Click to return this item{% else %}Click to view item details and return options{% endif %}"{% else %}style="background-color: #cfe2ff !important; border: 1px solid #b6d4fe !important; color: #084298 !important; padding: 12px 16px !important; border-radius: 4px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; margin-bottom: 16px !important; position: relative !important; z-index: 100 !important; width: 100% !important; min-height: 50px !important;"{% endif %}>
                <div style="display: flex !important; align-items: center !important; flex: 1 !important;">
                    <i class="fas {% if systemNotification.type == 'agreement_ready' %}fa-file-signature{% else %}fa-clock{% endif %}" style="margin-right: 8px !important; color: {% if systemNotification.type == 'agreement_ready' %}#0f5132{% else %}#084298{% endif %} !important;"></i>
                    <span style="color: {% if systemNotification.type == 'agreement_ready' %}#0f5132{% else %}#084298{% endif %} !important;">{{ systemNotification.message }}</span>
                    {% if systemNotification.message and 'Shall we send a reminder?' in systemNotification.message %}
                    <span style="margin-left: 8px !important; font-size: 12px !important; opacity: 0.8 !important;">(Click to send reminder)</span>
                    {% elseif systemNotification.itemId %}
                    <span style="margin-left: 8px !important; font-size: 12px !important; opacity: 0.8 !important;">{% if systemNotification.type and (systemNotification.type starts with 'return_' or systemNotification.type starts with 'owner_overdue' or 'overdue' in systemNotification.message|lower) %}(Click to return item){% elseif systemNotification.type == 'agreement_ready' %}(Click to sign agreement){% else %}(Click to view item){% endif %}</span>
                    {% endif %}
                </div>
                <div style="display: flex !important; gap: 8px !important; align-items: center !important; flex-shrink: 0 !important;">
                    <button type="button" id="dismiss-btn-{{ systemNotification.id }}" onclick="event.stopPropagation(); dismissNotification({{ systemNotification.id }})" title="Dismiss this reminder" style="background: {% if systemNotification.type == 'agreement_ready' %}#0f5132{% else %}#084298{% endif %} !important; color: white !important; border: 1px solid {% if systemNotification.type == 'agreement_ready' %}#0f5132{% else %}#084298{% endif %} !important; padding: 6px 12px !important; border-radius: 4px !important; font-size: 13px !important; cursor: pointer !important; display: block !important; visibility: visible !important; opacity: 1 !important; font-weight: bold !important; min-width: 70px !important;">
                        Dismiss
                    </button>
                    <button type="button" id="close-btn-{{ systemNotification.id }}" onclick="event.stopPropagation(); hideBlueBar()" aria-label="Close" style="background: transparent !important; border: none !important; color: {% if systemNotification.type == 'agreement_ready' %}#0f5132{% else %}#084298{% endif %} !important; font-size: 18px !important; cursor: pointer !important; padding: 2px 6px !important; display: block !important; visibility: visible !important; opacity: 1 !important; font-weight: bold !important;">
                        ×
                    </button>
                </div>
            </div>
            
            <style>
            /* Ensure dropdown menus always appear above notification bars */
            .dropdown-menu {
                z-index: 10000 !important;
            }
            
            /* Ensure Bootstrap modals and other overlays are properly layered */
            .modal {
                z-index: 10050 !important;
            }
            
            .modal-backdrop {
                z-index: 10040 !important;
            }
            </style>
            
            <script>
            // Ensure notification bar stays visible
            document.addEventListener('DOMContentLoaded', function() {
                const notificationBar = document.getElementById('blueNotificationBar');
                if (notificationBar) {
                    // Force visibility and prevent hiding
                    notificationBar.style.display = 'flex';
                    notificationBar.style.visibility = 'visible';
                    notificationBar.style.opacity = '1';
                    
                    // Log for debugging
                    console.log('Notification bar found and made visible');
                } else {
                    console.log('No notification bar found');
                }
            });
            </script>
            {% endif %}
        </div>
        
        <div class="row row-cols-2 row-cols-md-1 g-4">
            
            <!-- Left Column - Actions and User Items -->
            <div class="col-12 col-md-12 col-lg-6 col-xl-6 col-xxl-6">
                
                <!-- Actions Section -->
                <div class="row border border-success rounded-4 p-0 px-2 lh-1 mt-0 text-center" style="background-color: white;">
                    <span class="h5 giantish" style="line-height: 1.0;">Actions:<br></span>
                    
                    <!-- Row 1: Browse, Favorites, My Inventory -->
                    <div class="row g-1 mb-1">
                        <!-- Browse All -->
                        <div class="col-4 p-1" style="background-color: #f0f8f0; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/browse">
                                    <img src="/lendables/logo_browse_600.png" 
                                         class="hover-effect-target" alt="Browse All Lendables" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="Browse (and Sort, and Filter) the Community's Lendables, to find what you need!">
                                </a>
                            </div>
                        </div>
                        
                        <!-- Favorites -->
                        <div class="col-4 p-1" style="background-color: #fff0f5; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/browse?favorites=true&user={{ currentUser.id }}">
                                    <img src="/lendables/logo_favorites_600.png" 
                                         class="hover-effect-target" alt="Browse Favorites" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="Browse Your Favorite Lendable Items">
                                </a>
                            </div>
                        </div>
                        
                        <!-- My Inventory -->
                        <div class="col-4 p-1" style="background-color: #f3e5f5; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/my-inventory/{{ currentUser.id }}">
                                    <img src="/lendables/logo_myinventory_600.png" 
                                         class="hover-effect-target" alt="My Inventory" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="View and manage your complete lendable inventory">
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Row 2: Create, Ask for Item, Offer an Hour -->
                    <div class="row g-1">
                        <!-- Create New Item -->
                        <div class="col-4 p-1" style="background-color: #e8f5e8; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/create-item">
                                    <img src="/lendables/logo_create_600.png" 
                                         class="hover-effect-target" alt="Create New" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="Create a New Lendable Item to Offer to our Community">
                                </a>
                            </div>
                        </div>
                        
                        <!-- Ask for an Item -->
                        <div class="col-4 p-1" style="background-color: #f0f8ff; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/ask-item">
                                    <img src="/lendables/logo_ask_for_600.png" 
                                         class="hover-effect-target" alt="Ask for an Item" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="Ask the community for an item you need">
                                </a>
                            </div>
                        </div>
                        
                        <!-- Offer an Hour -->
                        <div class="col-4 p-1" style="background-color: #fff8e1; min-height: 120px;">
                            <div class="d-flex align-items-center justify-content-center h-100">
                                <a class="hover-effect-scale" href="/offer-hour">
                                    <img src="/lendables/logo_offerhour_600.png" 
                                         class="hover-effect-target" alt="Offer an Hour" style="display: block !important; width: 100%; max-width: 100px; height: auto;" 
                                         title="Offer your time and services to help community members">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Accordion Sections -->
                <div class="row row-cols-1 row-cols-md-1 g-1 pt-1">
                    
                    <!-- 1. My Lendables / My Items -->
                    <div class="col">
                        <div class="accordion" id="accordion2Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading2" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse2" aria-expanded="false" aria-controls="collapse2">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">({{ userItems|length }}) <a href="/my-items/{{ user.id }}/lendable" class="text-decoration-none" style="color: #1a4d1a;">My Lendable Items</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse2" aria-labelledby="heading2" data-bs-parent="#accordion2Example">
                                    <div class="accordion-body pb-0">
                                        {% if userItems and userItems|length > 0 %}
                                            <div class="row g-3">
                                                {% for item in userItems %}
                                                <div class="col-12">
                                                    <div class="card border-0 shadow-sm hover-card" style="cursor: pointer; transition: all 0.2s ease;" onclick="window.location.href='/item/{{ item.id }}'" onmouseover="this.style.backgroundColor='#f8f9fa'; this.style.borderColor='#007bff'" onmouseout="this.style.backgroundColor=''; this.style.borderColor=''">
                                                        <div class="card-body p-3">
                                                            <!-- First Row: Image | Title/Category | View Button -->
                                                            <div class="d-flex align-items-center mb-2">
                                                                {% if item.primaryLogo %}
                                                                <img src="/lendable_items/{{ item.thumbnailLogo ?: item.primaryLogo }}" 
                                                                     class="rounded me-2" 
                                                                     style="width: 120px; height: auto; max-height: 100px; object-fit: contain;"
                                                                     alt="{{ item.name }}"
                                                                     onerror="this.style.display='none'">
                                                                {% else %}
                                                                <div class="d-flex align-items-center justify-content-center rounded bg-light me-2"
                                                                     style="width: 120px; height: 80px; border: 1px solid #ddd;">
                                                                    <i class="fas fa-image text-muted" style="font-size: 2rem;"></i>
                                                                </div>
                                                                {% endif %}
                                                                <div class="flex-grow-1">
                                                                    <h6 class="card-title mb-1">{{ item.name }}</h6>
                                                                    <p class="text-muted small mb-0">{{ item.categoryName ?: 'Uncategorized' }}</p>
                                                                </div>
                                                                <div class="text-end">
                                                                    <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation()">View</a>
                                                                    {% if item.owner == user.id %}
                                                                        <a href="/edit-item/{{ item.id }}" class="btn btn-outline-success btn-sm ms-1" onclick="event.stopPropagation()">Edit</a>
                                                                    {% endif %}
                                                                </div>
                                                            </div>
                                                            <!-- Second Row: Description spanning full width -->
                                                            <div class="row">
                                                                <div class="col-12">
                                                                    <p class="card-text small text-muted mb-2">{{ item.description }}</p>
                                                                    <div class="d-flex align-items-center gap-2">
                                                                        {% if item.pricePerDay and item.pricePerDay > 0 %}
                                                                            <span class="badge bg-danger badge-nowrap">Rentable</span>
                                                                            <small class="text-muted">${{ item.pricePerDay }}/day</small>
                                                                        {% else %}
                                                                            <span class="badge bg-success badge-nowrap">Lendable</span>
                                                                        {% endif %}
                                                                        <span class="badge" id="status-{{ item.id }}">Loading...</span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                {% endfor %}
                                            </div>
                                        {% else %}
                                            <div class="text-center py-4">
                                                <i class="fas fa-box-open text-muted mb-3" style="font-size: 3rem;"></i>
                                                <h6 class="text-muted">No items shared yet</h6>
                                                <p class="small text-muted">Create your first lendable item to start sharing with the community!</p>
                                                <a href="/create-item" class="btn btn-primary">Create First Item</a>
                                            </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 2. Borrow Requests (with dusty red background when requests exist) -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion5Example">
                            <div class="accordion-item" id="borrowRequestsAccordion">
                                <h3 class="accordion-header px-2 py-0" id="heading5" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse5" aria-expanded="false" aria-controls="collapse5">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">(<span id="requestCount" style="color: #1a4d1a;">-</span>) Borrow Requests from Others</span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse5" aria-labelledby="heading5" data-bs-parent="#accordion5Example">
                                    <div class="accordion-body pb-0" id="borrowRequestsContent">
                                        <span class="h6">Loading borrow requests...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 3. Items I'm Borrowing -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion1Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading1" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">(<span id="borrowedCount" style="color: #1a4d1a;">-</span>) <a href="/my-items/{{ user.id }}/borrowed" class="text-decoration-none" style="color: #1a4d1a;">Items I'm Borrowing</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse1" aria-labelledby="heading1" data-bs-parent="#accordion1Example">
                                    <div class="accordion-body pb-0" id="borrowedItemsContent">
                                        <span class="h6">Loading borrowed items...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 4. My Items: Approved & Out on Loan -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion3Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading3" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse3" aria-expanded="false" aria-controls="collapse3">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">(<span id="loanCount" style="color: #1a4d1a;">-</span>) <a href="/my-items/{{ user.id }}/loaned" class="text-decoration-none" style="color: #1a4d1a;">My Items: Approved & Out on Loan</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse3" aria-labelledby="heading3" data-bs-parent="#accordion3Example">
                                    <div class="accordion-body pb-0" id="activeLoansContent">
                                        <span class="h6">Loading loans...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 5. My Wish List -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion4Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading4" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse4" aria-expanded="false" aria-controls="collapse4">
                                        {% set requestCount = 0 %}
                                        {% if allUserItems %}
                                            {% for item in allUserItems %}
                                                {% if item.isRequest %}
                                                    {% set requestCount = requestCount + 1 %}
                                                {% endif %}
                                            {% endfor %}
                                        {% endif %}
                                        <span class="animate-target me-2" style="color: #1a4d1a;">({{ requestCount }}) <a href="/my-items/{{ user.id }}/requests" class="text-decoration-none" style="color: #1a4d1a;">My Wish List</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse4" aria-labelledby="heading4" data-bs-parent="#accordion4Example">
                                    <div class="accordion-body pb-0">
                                        {% set requestItems = [] %}
                                        {% for item in allUserItems %}
                                            {% if item.isRequest %}
                                                {% set requestItems = requestItems|merge([item]) %}
                                            {% endif %}
                                        {% endfor %}
                                        
                                        {% if requestItems|length > 0 %}
                                            <div class="row g-2">
                                                {% for item in requestItems|slice(0, 3) %}
                                                    <div class="col-12">
                                                        <div class="card border-0 shadow-sm hover-card" style="cursor: pointer; transition: all 0.2s ease;" onclick="window.location.href='/item/{{ item.id }}'" onmouseover="this.style.backgroundColor='#f8f9fa'; this.style.borderColor='#007bff'" onmouseout="this.style.backgroundColor=''; this.style.borderColor=''">
                                                            <div class="card-body p-2 d-flex align-items-center">
                                                                <div class="me-3">
                                                                    <img src="/lendables/logo_askfor_600.png" alt="Ask For" style="width: 100px !important; height: 100px !important; object-fit: contain; border-radius: 50%;" class="wishlist-logo">
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <h6 class="card-title mb-1 small">{{ item.name }}</h6>
                                                                    <p class="card-text text-muted small mb-0">
                                                                        {{ item.description|length > 50 ? item.description|slice(0, 50) ~ '...' : item.description }}
                                                                    </p>
                                                                </div>
                                                                <div>
                                                                    <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation()">View</a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                {% endfor %}
                                            </div>
                                            {% if requestItems|length > 3 %}
                                                <div class="text-center mt-2">
                                                    <a href="/my-items/{{ user.id }}/requests" class="btn btn-outline-primary btn-sm">View All Requests</a>
                                                </div>
                                            {% endif %}
                                        {% else %}
                                            <span class="h6">You have no Wish List. Do you want to <a href="/ask-item">Create a Requested Item</a>?</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 6. Draft Items -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion6Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading6" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse6" aria-expanded="false" aria-controls="collapse6">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">(-) <a href="/my-items/{{ user.id }}/drafts" class="text-decoration-none" style="color: #1a4d1a;">Draft Items</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse6" aria-labelledby="heading6" data-bs-parent="#accordion6Example">
                                    <div class="accordion-body pb-0">
                                        <span class="h6">You have no Drafts. Do you want to <a href="#" onclick="LocalLendables.showToast('Coming Soon', 'Create Draft Item feature coming soon!')">Create a Draft Item</a>?</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 7. My Upcoming Hours Offered -->
                    <div class="col mt-1">
                        <div class="accordion" id="accordion7Example">
                            <div class="accordion-item">
                                <h3 class="accordion-header px-2 py-0" id="heading7" style="background-color: #90EE90;">
                                    <button type="button" class="accordion-button animate-underline" data-bs-toggle="collapse" data-bs-target="#collapse7" aria-expanded="false" aria-controls="collapse7">
                                        <span class="animate-target me-2" style="color: #1a4d1a;">({{ userHourOfferingsCount | default(0) }}) <a href="/browse-hours?tab=my-hours" class="text-decoration-none" style="color: #1a4d1a;">My Upcoming Offered Hours</a></span>
                                    </button>
                                </h3>
                                <div class="accordion-collapse collapse" id="collapse7" aria-labelledby="heading7" data-bs-parent="#accordion7Example">
                                    <div class="accordion-body pb-0">
                                        {% if userHourOfferingsCount > 0 %}
                                            <span class="h6">You have upcoming hour offerings on {{ userHourOfferingsCount }} day{{ userHourOfferingsCount != 1 ? 's' : '' }}. <a href="/browse-hours?tab=my-hours">View and manage them</a>.</span>
                                        {% else %}
                                            <span class="h6">You have no upcoming hour offerings. <a href="/offer-hour">Offer an hour</a> to help someone in your community!</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Right Column - Newest Lendables -->
            <div class="col-12 col-md-12 col-lg-6 col-xl-6 col-xxl-6">
                <div class="row border border-success rounded-4 p-0 px-2 table-responsive" style="background-color: white;">
                    <div class="col-12 py-0 my-0 align-self-center text-center">
                        <div class="d-flex flex-column align-items-center justify-content-center">
                            <span class="h5 giantish" style="line-height: 1.0;">Newest Lendables:<br></span>
                        </div>
                    </div>
                </div>
                
                <!-- Newest Lendables List - Only showing Lendables, not Rentables -->
                {% set lendableItems = [] %}
                {% for item in allItems %}
                    {% if not item.pricePerDay or item.pricePerDay == 0 %}
                        {% set lendableItems = lendableItems|merge([item]) %}
                    {% endif %}
                {% endfor %}
                
                {% if lendableItems and lendableItems|length > 0 %}
                    <div class="row g-3 mt-2">
                        {% for item in lendableItems|slice(0, 10) %}
                        <div class="col-12">
                            <div class="card border-0 shadow-sm h-100 hover-card {% if item.isRequest %}asking-for-item{% endif %} position-relative" style="cursor: pointer;" onclick="window.location.href='/item/{{ item.id }}'">
                                <div class="card-body p-1">
                                    <div class="row g-3 align-items-center">
                                        <!-- Left: Image (40%) -->
                                        <div class="col-5">
                                            {% set itemImage = item.thumbnailLogo ?: item.primaryLogo ?: item.imageUrl %}
                                            {% if itemImage %}
                                            {% if item.isRequest %}
                                            <div class="d-flex align-items-center justify-content-center" style="height: 100px;">
                                                <img src="/lendable_items/{{ itemImage }}" 
                                                     class="rounded" 
                                                     style="max-width: 120px; max-height: 100px; object-fit: contain; padding: 3px;"
                                                     alt="{{ item.name }}"
                                                     onerror="this.style.display='none'">
                                            </div>
                                            {% else %}
                                            <img src="/lendable_items/{{ itemImage }}" 
                                                 class="rounded" 
                                                 style="width: 100%; height: auto; object-fit: contain; padding: 3px;"
                                                 alt="{{ item.name }}"
                                                 onerror="this.style.display='none'">
                                            {% endif %}
                                            {% else %}
                                            <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 100px;">
                                                <i class="fas fa-image text-muted" style="font-size: 1.5rem;"></i>
                                            </div>
                                            {% endif %}
                                        </div>
                                        <!-- Right: Text (60%) -->
                                        <div class="col-7">
                                            {% if item.isRequest %}
                                                <div class="card-title mb-1 fw-bold text-muted medium">Asking For:</div>
                                            {% endif %}
                                            <h5 class="card-title mb-2 fw-bold medium">{{ item.name }}{% if item.isRequest %}?{% endif %}</h5>
                                            {% if item.description %}
                                            <p class="card-text mb-2 medium" style="line-height: 1.4;">
                                                {{ item.description|length > 50 ? item.description|slice(0, 50) ~ '...' : item.description }}
                                            </p>
                                            {% endif %}
                                            <div class="d-flex justify-content-between align-items-end">
                                                <p class="text-muted mb-0 medium">by {{ item.ownerShowName ?: item.ownerFirstName ?: "Member" }}</p>
                                                <div class="text-end">
                                                    {% if item.isRequest %}
                                                    <div class="badge bg-warning text-dark badge-nowrap">Asking For...</div>
                                                    {% elseif item.pricePerDay and item.pricePerDay > 0 %}
                                                    <div class="badge bg-success mb-1">${{ item.pricePerDay }}/day</div>
                                                    <div class="badge bg-info badge-nowrap">Rentable</div>
                                                    {% else %}
                                                    <div class="badge bg-success badge-nowrap">Lendable</div>
                                                    {% endif %}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Favorites Heart Button - Upper Right Corner -->
                                <div class="position-absolute top-0 end-0 p-2" style="z-index: 10;">
                                    <button class="btn btn-link p-0 border-0 favorite-btn" 
                                            data-item-id="{{ item.id }}" 
                                            data-user-id="{{ currentUser.id }}"
                                            title="Favorite me for later!"
                                            style="background: rgba(255,255,255,0.9); border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 8px rgba(0,0,0,0.2); cursor: pointer; pointer-events: auto;"
                                            onclick="handleFavoriteClick(event, {{ item.id }});">
                                        <i class="fas fa-heart" style="color: #ccc; font-size: 1.0rem; transition: color 0.3s; pointer-events: none;"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                {% else %}
                    <div class="text-center py-4">
                        <i class="fas fa-heart text-muted mb-3" style="font-size: 2rem;"></i>
                        <h6 class="text-muted">No lendable items available</h6>
                        <p class="small text-muted">Check back later for new items from the community!</p>
                    </div>
                {% endif %}
                
                <!-- Browse All Items Button -->
                <div class="text-center mt-4 mb-3">
                    <a href="/browse" class="btn btn-outline-primary">
                        <img src="/lendables/logo_browse_600.png" alt="Browse" style="height: 60px; width: auto;" class="me-2">Browse All {{ totalItemCount ?: 0 }} Items
                    </a>
                </div>
                    </a>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- Messages Modal -->
<div class="modal fade" id="messagesModal" tabindex="-1" aria-labelledby="messagesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="messagesModalLabel">Unread Messages</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="messagesModalBody">
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- General Modal for Borrowed Items -->
<div class="modal fade" id="generalModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="generalModalTitle">Modal Title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="generalModalBody">
                <!-- Content will be populated by JavaScript -->
            </div>
        </div>
    </div>
</div>

<script>
// Load borrowed items and borrow requests when accordion is opened
document.addEventListener('DOMContentLoaded', function() {
    loadBorrowingCounts();
    loadItemStatuses();
    loadActiveLoansCount(); // Load the count immediately
    loadInitialFavorites(); // Load favorite states for heart icons
    // loadNotifications(); // Disabled - using server-rendered notifications
    
    // Load data when accordions are expanded - add null checks to prevent errors
    const collapse1 = document.getElementById('collapse1');
    const collapse3 = document.getElementById('collapse3');
    const collapse5 = document.getElementById('collapse5');
    
    if (collapse1) collapse1.addEventListener('show.bs.collapse', loadBorrowedItems);
    if (collapse3) collapse3.addEventListener('show.bs.collapse', loadActiveLoans);
    if (collapse5) collapse5.addEventListener('show.bs.collapse', loadBorrowRequests);
});

// PERFORMANCE OPTIMIZATION: Use consolidated dashboard API
async function loadBorrowingCounts() {
    try {
        console.log('Loading dashboard data via consolidated API...');
        
        // Single API call instead of multiple separate requests
        const response = await fetch('/api/dashboard/{{ user.id }}');
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to load dashboard data');
        }
        
        const { activeLoans, borrowRequests } = result.data;
        
        // Process borrowed items (activeLoans)
        const borrowedResult = { success: true, loans: activeLoans };
        if (borrowedResult.success) {
            document.getElementById('borrowedCount').textContent = borrowedResult.loans.length;
            
            // Check for overdue borrowed items
            const overdueItems = borrowedResult.loans.filter(loan => {
                // Check both the is_overdue flag and status
                return loan.is_overdue === true || loan.status === 'overdue';
            });
            
            // Change background to red if there are overdue borrowed items
            const borrowedItemsHeader = document.getElementById('heading1');
            if (borrowedItemsHeader) {
                if (overdueItems.length > 0) {
                    // Set header to red with black text for overdue items
                    borrowedItemsHeader.style.setProperty('background-color', '#dc3545', 'important');
                    // Change text color to black for better readability
                    const textSpan = borrowedItemsHeader.querySelector('.animate-target');
                    const countSpan = document.getElementById('borrowedCount');
                    if (textSpan) {
                        textSpan.style.setProperty('color', '#000000', 'important');
                    }
                    if (countSpan) {
                        countSpan.style.setProperty('color', '#000000', 'important');
                    }
                } else {
                    // Reset header to green
                    borrowedItemsHeader.style.backgroundColor = '#90EE90'; // Default bright green
                    // Reset text color to dark green
                    const textSpan = borrowedItemsHeader.querySelector('.animate-target');
                    const countSpan = document.getElementById('borrowedCount');
                    if (textSpan) textSpan.style.color = '#1a4d1a';
                    if (countSpan) countSpan.style.color = '#1a4d1a';
                }
            }
        }
        
        // Process borrow requests using consolidated data
        const requestsResult = { success: true, requests: borrowRequests };
        if (requestsResult.success) {
            const pendingRequests = requestsResult.requests.filter(r => r.status === 'pending').length;
            document.getElementById('requestCount').textContent = pendingRequests;
            
            // Change background to red if there are pending requests
            const borrowRequestsHeader = document.getElementById('heading5');
            if (borrowRequestsHeader) {
                if (pendingRequests > 0) {
                    // Set header to red with black text
                    borrowRequestsHeader.style.setProperty('background-color', '#dc3545', 'important');
                    // Change text color to black for better readability
                    const textSpan = borrowRequestsHeader.querySelector('.animate-target');
                    const countSpan = document.getElementById('requestCount');
                    if (textSpan) {
                        textSpan.style.setProperty('color', '#000000', 'important');
                    }
                    if (countSpan) {
                        countSpan.style.setProperty('color', '#000000', 'important');
                    }
                } else {
                    // Reset header to green
                    borrowRequestsHeader.style.backgroundColor = '#90EE90'; // Default bright green
                    // Reset text color to dark green
                    const textSpan = borrowRequestsHeader.querySelector('.animate-target');
                    const countSpan = document.getElementById('requestCount');
                    if (textSpan) textSpan.style.color = '#1a4d1a';
                    if (countSpan) countSpan.style.color = '#1a4d1a';
                }
            }
        }
    } catch (error) {
        console.error('Error loading borrowing counts:', error);
        document.getElementById('borrowedCount').textContent = '0';
        document.getElementById('requestCount').textContent = '0';
    }
}

// Load borrowed items
async function loadBorrowedItems() {
    try {
        const response = await fetch(`/api/loans/active/{{ user.id }}`);
        const result = await response.json();
        
        const content = document.getElementById('borrowedItemsContent');
        
        if (result.success && result.loans.length > 0) {
            content.innerHTML = `
                <div class="row g-2">
                    ${result.loans.map(loan => `
                        <div class="col-12">
                            <div class="card border-0 shadow-sm hover-card" style="cursor: pointer;" onclick="window.location.href='/item/${loan.itemId}'">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="d-flex">
                                            <img src="/lendable_items/${loan.item_image || 'default-placeholder.jpg'}" 
                                                 alt="${loan.item_name}" 
                                                 class="me-3 rounded" 
                                                 style="width: 60px; height: 60px; object-fit: cover; flex-shrink: 0;"
                                                 onerror="this.src='/lendable_items/default-placeholder.jpg'">
                                            <div>
                                                <h6 class="mb-1">${loan.item_name}</h6>
                                                <small class="text-muted">From: ${loan.owner_show_name || loan.owner_name || 'Member'}</small><br>
                                                <small class="text-muted">${parseUTCDate(loan.start_date).toLocaleDateString()} - ${parseUTCDate(loan.end_date).toLocaleDateString()}</small><br>
                                                <span class="badge ${loan.status === 'overdue' ? 'bg-danger' : loan.status === 'active' ? 'bg-success text-dark' : loan.status === 'return_requested' ? 'bg-warning text-dark' : 'bg-warning'}">${loan.status === 'overdue' ? 'overdue' : loan.status === 'return_requested' ? 'return requested' : loan.status === 'pending' ? 'Waiting for Agreement Signature' : loan.status === 'approved' ? 'Ready for Pickup' : loan.status}</span>
                                            </div>
                                        </div>
                                        <div>
                                            ${loan.agreementId ? `
                                                <a href="/agreement/${loan.agreementId}" class="btn btn-sm ${loan.agreementStatus === 'pending' ? 'btn-success' : 'btn-outline-info'} me-1" onclick="event.stopPropagation()" title="${loan.agreementStatus === 'pending' ? 'Sign Loan Agreement' : 'View Loan Agreement'}">
                                                    <i class="fas ${loan.agreementStatus === 'pending' ? 'fa-file-signature' : 'fa-file-contract'} me-1"></i>${loan.agreementStatus === 'pending' ? 'Sign Agreement' : 'Agreement'}
                                                </a>
                                            ` : ''}
                                            ${(loan.status === 'active' || loan.status === 'overdue') ? `
                                                <button class="btn btn-sm ${loan.status === 'overdue' ? 'btn-danger' : 'btn-warning text-dark'} me-1" onclick="event.stopPropagation(); window.location.href='/return/${loan.itemId}?userId=${loan.borrowerId}'">
                                                    <i class="fas fa-undo me-1"></i>Return ${loan.status === 'overdue' ? 'ASAP' : ''}
                                                </button>
                                            ` : ''}
                                            ${(loan.status === 'pending' || loan.status === 'approved') ? `
                                                <button class="btn btn-sm btn-outline-danger" onclick="event.stopPropagation(); deleteBorrowedItem(${loan.id}, '${loan.item_name}')" title="Delete (only available before pickup)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            ` : ''}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        } else {
            content.innerHTML = '<span class="h6">You have no Borrowed Items. Do you want to <a href="/browse">Browse the Available Items</a>?</span>';
        }
    } catch (error) {
        console.error('Error loading borrowed items:', error);
        document.getElementById('borrowedItemsContent').innerHTML = '<span class="text-danger">Error loading borrowed items</span>';
    }
}

// Load borrow requests
async function loadBorrowRequests() {
    try {
        const response = await fetch(`/api/borrow-requests/owner/{{ user.id }}`);
        const result = await response.json();
        
        const content = document.getElementById('borrowRequestsContent');
        
        if (result.success && result.requests.length > 0) {
            content.innerHTML = `
                <div class="row g-2">
                    ${result.requests.map(request => `
                        <div class="col-12">
                            <div class="card border-0 shadow-sm hover-card" style="cursor: pointer; transition: all 0.2s ease;" onclick="window.location.href='/borrow-request/${request.id}/respond'" onmouseover="this.style.backgroundColor='#f8f9fa'; this.style.borderColor='#007bff'" onmouseout="this.style.backgroundColor=''; this.style.borderColor=''">
                                <div class="card-body p-2">
                                    <div class="d-flex align-items-center mb-1">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">${request.itemName || request.item_name || 'Unknown Item'}</h6>
                                            <p class="text-muted small mb-0">Requested by: ${request.borrowerName || request.borrower_name || 'Unknown User'}</p>
                                        </div>
                                        <div class="text-end">
                                            ${request.status === 'pending' ? `
                                                <a href="/borrow-request/${request.id}/respond" class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation()">View</a>
                                            ` : `
                                                <a href="/borrow-request/${request.id}/respond" class="btn btn-outline-secondary btn-sm" onclick="event.stopPropagation()">View</a>
                                            `}
                                            ${(request.status === 'pending' || request.status === 'approved') ? `
                                                <button class="btn btn-outline-danger btn-sm" onclick="event.stopPropagation(); deleteBorrowRequest(${request.id})" title="Delete this request (only available before pickup)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            ` : ''}
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-12">
                                            <small class="text-muted">${parseUTCDate(request.startDate || request.start_date).toLocaleDateString()} - ${parseUTCDate(request.endDate || request.end_date).toLocaleDateString()}</small><br>
                                            ${request.message ? `<p class="small text-muted mb-1">"${request.message}"</p>` : ''}
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="badge ${request.status === 'pending' ? 'bg-warning text-dark' : request.status === 'approved' ? 'bg-success text-dark' : 'bg-secondary'}">${request.status === 'pending' ? 'Approval Pending' : request.status.charAt(0).toUpperCase() + request.status.slice(1)}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        } else {
            content.innerHTML = '<span class="h6">No borrow requests at this time.</span>';
        }
    } catch (error) {
        console.error('Error loading borrow requests:', error);
        document.getElementById('borrowRequestsContent').innerHTML = '<span class="text-danger">Error loading borrow requests</span>';
    }
}

async function initiateReturn(loanId) {
    // Show thank-you reminder with comment option
    const result = await Swal.fire({
        title: 'Ready to Return?',
        html: `
            <div class="text-start">
                <p class="mb-3">Great! You're ready to return this item.</p>
                <div class="alert alert-info">
                    <i class="fas fa-heart text-danger me-2"></i>
                    <strong>Community Tip:</strong> A thank-you gesture is always appreciated! 
                    Consider leaving a kind comment or bringing a small treat like cookies.
                </div>
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-comment me-1"></i>Leave a thank-you message (optional):</label>
                    <textarea class="form-control" id="thank-you-message" rows="3" 
                              placeholder="Thanks Pete! That set of stakes really helped take care of the vampire infestation!"></textarea>
                    <small class="text-muted">Your message will be shared with the lender to show appreciation.</small>
                </div>
                <p class="mb-0">Click "Initiate Return" to notify the owner.</p>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Initiate Return',
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        width: 600,
        preConfirm: () => {
            return {
                thankYouMessage: document.getElementById('thank-you-message').value.trim()
            };
        }
    });

    if (result.isConfirmed) {
        try {
            const response = await fetch(`/api/loans/${loanId}/return`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    thankYouMessage: result.value.thankYouMessage
                })
            });
            
            const data = await response.json();
            if (data.success) {
                Swal.fire({
                    title: 'Return Initiated!',
                    text: 'The owner has been notified. They will confirm when they receive the item.',
                    icon: 'success',
                    confirmButtonColor: '#28a745'
                });
                loadBorrowedItems(); // Refresh the list
                loadBorrowingCounts(); // Update counts
            } else {
                Swal.fire('Error', data.error || 'Failed to initiate return', 'error');
            }
        } catch (error) {
            console.error('Error initiating return:', error);
            Swal.fire('Error', 'Failed to initiate return', 'error');
        }
    }
}

async function deleteBorrowRequest(requestId) {
    if (!confirm('Are you sure you want to delete this borrow request? This action cannot be undone.')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/borrow-requests/${requestId}`, {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' }
        });
        
        const result = await response.json();
        if (result.success) {
            LocalLendables.showToast('Success', 'Borrow request deleted successfully.', 'success');
            loadBorrowRequests(); // Refresh the list
            loadBorrowingCounts(); // Update counts
        } else {
            LocalLendables.showToast('Error', 'Error: ' + result.error, 'error');
        }
    } catch (error) {
        console.error('Error deleting borrow request:', error);
        LocalLendables.showToast('Error', 'Failed to delete borrow request', 'error');
    }
}

async function loadNotifications() {
    try {
        const response = await fetch('/api/notifications/{{ user.id }}');
        const result = await response.json();
        
        // Don't replace notification area content - it's already rendered server-side
        // Just update counts and other dynamic elements if needed
        console.log('Notifications loaded but not replacing server-rendered content');
        return;
        
        if (result.success && result.notifications.length > 0) {
            const notificationArea = document.getElementById('notification-area');
            const unreadNotifications = result.notifications.filter(n => !n.isRead);
            
            if (unreadNotifications.length > 0) {
                notificationArea.innerHTML = `
                    <div class="d-flex justify-content-center">
                        <div style="width: 50%;">
                            ${unreadNotifications.map(notification => {
                                let actionButton = '';
                                if (notification.type === 'borrow_request' && notification.relatedType === 'borrow_request') {
                                    // Extract item ID from the borrow request to link to item detail page
                                    actionButton = `<a href="/borrow-request/${notification.relatedId}/respond" class="btn btn-primary me-2" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">Respond</a>`;
                                    // Add direct link to item detail page using item_id from notification data
                                    if (notification.itemId) {
                                        actionButton += `<a href="/item/${notification.itemId}" class="btn btn-outline-primary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">View Item</a>`;
                                    } else {
                                        // Fallback: extract item name and search
                                        const itemMatch = notification.message.match(/your "([^"]+)"/);
                                        if (itemMatch) {
                                            actionButton += `<a href="#" onclick="goToBorrowSection('${itemMatch[1]}')" class="btn btn-outline-primary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">View Item</a>`;
                                        }
                                    }
                                }
                                
                                return `
                                    <div class="alert alert-info alert-dismissible fade show d-flex justify-content-between align-items-center" role="alert" style="font-size: 0.8rem; padding: 0.5rem 0.75rem; min-height: auto;">
                                        <div class="d-flex align-items-center flex-grow-1">
                                            <i class="fas fa-bell me-2" style="font-size: 0.7rem;"></i>
                                            <div class="flex-grow-1">
                                                <div style="font-size: 0.75rem;"><strong>${notification.title}</strong></div>
                                                <div style="font-size: 0.7rem; color: #6c757d;">${notification.message}</div>
                                            </div>
                                            <div class="ms-2">
                                                ${actionButton}
                                            </div>
                                        </div>
                                        <button type="button" class="btn-close" aria-label="Close" onclick="markNotificationRead(${notification.id})" style="font-size: 0.6rem; padding: 0.25rem;"></button>
                                    </div>
                                `;
                            }).join('')}
                        </div>
                    </div>
                `;
            } else {
                notificationArea.innerHTML = '';
            }
        } else {
            notificationArea.innerHTML = '';
        }
    } catch (error) {
        console.error('Error loading notifications:', error);
    }
}

// Function to navigate to item detail page borrow section
function goToBorrowSection(itemName) {
    // Find the item by name and navigate to its detail page
    fetch('/api/items/search?name=' + encodeURIComponent(itemName))
        .then(response => response.json())
        .then(data => {
            if (data.success && data.item) {
                window.location.href = `/item/${data.item.id}#borrow-section`;
            } else {
                // Fallback: go to browse page
                window.location.href = '/browse';
            }
        })
        .catch(error => {
            console.error('Error finding item:', error);
            window.location.href = '/browse';
        });
}

async function markNotificationRead(notificationId) {
    try {
        await fetch(`/api/notifications/${notificationId}/read`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
    } catch (error) {
        console.error('Error marking notification as read:', error);
    }
}

function hideBlueBar() {
    document.getElementById('blueNotificationBar').style.display = 'none';
}

async function dismissNotification(notificationId) {
    try {
        const response = await fetch(`/api/notifications/${notificationId}/dismiss`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            // Hide the blue bar immediately
            document.getElementById('blueNotificationBar').style.display = 'none';
            // Force page reload to ensure all notification states are updated
            setTimeout(() => {
                window.location.reload();
            }, 500);
        } else {
            console.error('Failed to dismiss notification');
        }
    } catch (error) {
        console.error('Error dismissing notification:', error);
    }
}

async function markMessageAsRead(messageId, isSystemNotification) {
    try {
        let response;
        
        if (isSystemNotification) {
            // For system notifications, dismiss them permanently
            const notificationId = messageId.replace('system_', '');
            response = await fetch(`/api/notifications/${notificationId}/dismiss`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
        } else {
            // For regular chat messages, mark as read
            response = await fetch(`/api/messages/${messageId}/mark-read`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
        }

        if (response.ok) {
            // Remove the message from dropdown immediately
            const messageCard = document.getElementById(`message-card-${messageId}`);
            if (messageCard) {
                messageCard.remove();
            }
            
            // Check if dropdown is now empty
            const remainingCards = document.querySelectorAll('[id^="message-card-"]');
            if (remainingCards.length === 0) {
                document.getElementById('messagesModalBody').innerHTML = '<p class="text-center text-muted">No unread messages</p>';
            }
            
            // Refresh the dropdown after a brief delay
            setTimeout(() => {
                fetchUnreadMessages();
            }, 300);
        } else {
            console.error('Failed to mark message as read');
        }
    } catch (error) {
        console.error('Error marking message as read:', error);
    }
}

async function deleteBorrowedItem(borrowId, itemName) {
    const result = await Swal.fire({
        title: 'Delete Borrowed Item',
        text: `Are you sure you want to remove "${itemName}" from your borrowed items list?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d'
    });

    if (result.isConfirmed) {
        try {
            const response = await fetch(`/api/borrowed-items/${borrowId}`, {
                method: 'DELETE'
            });
            
            const data = await response.json();
            if (data.success) {
                Swal.fire({
                    title: 'Deleted!',
                    text: 'The item has been removed from your borrowed items.',
                    icon: 'success',
                    confirmButtonColor: '#28a745'
                });
                loadBorrowedItems(); // Refresh the list
                loadNotifications(); // Refresh notifications
            } else {
                Swal.fire('Error', data.error || 'Failed to delete item', 'error');
            }
        } catch (error) {
            console.error('Error deleting borrowed item:', error);
            Swal.fire('Error', 'Failed to delete item', 'error');
        }
    }
}

async function confirmReturn(trackingId, itemName) {
    const result = await Swal.fire({
        title: 'Confirm Item Return',
        html: `
            <p>Confirm that <strong>${itemName}</strong> has been returned.</p>
            <div class="mb-3">
                <label class="form-label">Item Condition:</label>
                <select class="form-select" id="return-condition">
                    <option value="excellent">Returned and in fine shape</option>
                    <option value="good">Good condition</option>
                    <option value="fair">Fair condition</option>
                    <option value="damaged">Damaged</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Notes (optional):</label>
                <textarea class="form-control" id="return-notes" rows="2" placeholder="Any additional notes..."></textarea>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Complete Return',
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        preConfirm: () => {
            const condition = document.getElementById('return-condition').value;
            const notes = document.getElementById('return-notes').value;
            return { condition, notes };
        }
    });

    if (result.isConfirmed) {
        try {
            const response = await fetch(`/api/loans/${trackingId}/confirm-return`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(result.value)
            });
            
            const data = await response.json();
            if (data.success) {
                Swal.fire({
                    title: 'Return Completed!',
                    text: 'The loan has been completed and both parties have been notified.',
                    icon: 'success',
                    confirmButtonColor: '#28a745'
                });
                loadItemStatuses(); // Refresh the status
                loadNotifications(); // Refresh notifications
            } else {
                Swal.fire('Error', data.error || 'Failed to complete return', 'error');
            }
        } catch (error) {
            console.error('Error confirming return:', error);
            Swal.fire('Error', 'Failed to complete return', 'error');
        }
    }
}

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

async function loadActiveLoans() {
    try {
        const response = await fetch(`/api/loans/owner/{{ user.id }}`);
        const result = await response.json();
        
        console.log('Active loans API response:', result);
        
        const content = document.getElementById('activeLoansContent');
        const countElement = document.querySelector('#heading3 .animate-target');
        
        if (result.success && result.loans && result.loans.length > 0) {
            countElement.textContent = `(${result.loans.length}) My Items: Approved & Out on Loan`;
            
            // Build content using DOM manipulation instead of template literals
            const containerDiv = document.createElement('div');
            containerDiv.className = 'row g-2';
            
            result.loans.forEach(loan => {
                console.log('=== DASHBOARD DATE DEBUG ===');
                console.log('Raw borrowedDate:', loan.borrowedDate);
                console.log('Raw expectedReturnDate:', loan.expectedReturnDate);
                
                const colDiv = document.createElement('div');
                colDiv.className = 'col-12';
                
                const cardDiv = document.createElement('div');
                cardDiv.className = 'card border-0 shadow-sm';
                
                const cardBodyDiv = document.createElement('div');
                cardBodyDiv.className = 'card-body p-2';
                
                // Create content
                const itemName = loan.itemName || 'Unknown Item';
                const borrowerName = loan.borrowerName || 'Unknown User';
                
                // Enhanced status handling including overdue logic
                let statusClass, statusText;
                if (loan.is_overdue) {
                    statusClass = 'bg-danger';
                    statusText = 'Overdue';
                } else if (loan.status === 'active') {
                    statusClass = 'bg-warning';
                    statusText = 'Out';
                } else if (loan.status === 'approved') {
                    statusClass = 'bg-success';
                    statusText = 'Approved';
                } else {
                    statusClass = 'bg-info';
                    statusText = 'Reserved';
                }
                
                const startDate = loan.borrowedDate ? parseUTCDate(loan.borrowedDate).toLocaleDateString() : 'Unknown';
                const endDate = loan.expectedReturnDate ? parseUTCDate(loan.expectedReturnDate).toLocaleDateString() : 'Unknown';
                
                console.log('Parsed startDate with UTC:', startDate);
                console.log('Parsed endDate with UTC:', endDate);
                
                // Check if the loan is in the future
                const borrowedDate = loan.borrowedDate ? parseUTCDate(loan.borrowedDate) : null;
                const today = new Date();
                today.setHours(0, 0, 0, 0); // Start of today
                const isFutureLoan = borrowedDate && borrowedDate > today;
                
                const pickupText = loan.pickedUp ? '✓ Picked up' : 'Not yet picked up';
                const pickupClass = loan.pickedUp ? 'text-success' : 'text-muted';
                
                // Determine thumbnail image
                const thumbnailImg = loan.thumbnail || loan.primaryImage 
                    ? `/lendable_items/${loan.thumbnail || loan.primaryImage}` 
                    : '/lendable_items/default-placeholder.jpg';
                
                cardBodyDiv.innerHTML = `
                    <div class="d-flex align-items-center mb-2">
                        <img src="${thumbnailImg}" 
                             alt="${itemName} thumbnail" 
                             style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px; margin-right: 12px;"
                             onerror="this.src='/lendable_items/default-placeholder.jpg'">
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${itemName}</h6>
                            <p class="text-muted small mb-0">${isFutureLoan ? 'To be borrowed by' : 'Borrowed by'}: ${borrowerName}</p>
                            <small class="text-muted">${startDate} - ${endDate}</small>
                            <br><small class="${pickupClass}">${pickupText}</small>
                        </div>
                        <div class="text-end">
                            <span class="badge ${statusClass}">${statusText}</span>
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-primary btn-sm flex-grow-1 view-item-btn" data-item-id="${loan.itemId}">
                            <i class="fas fa-eye me-1"></i>View Item
                        </button>
                        ${loan.agreementId ? `
                            <a href="/agreement/${loan.agreementId}" class="btn btn-outline-info btn-sm" title="View Loan Agreement">
                                <i class="fas fa-file-contract me-1"></i>Agreement
                            </a>
                        ` : ''}
                        <button class="btn btn-success btn-sm push-return-btn" data-loan-id="${loan.id}" data-item-name="${itemName}" data-borrower-name="${borrowerName}">
                            <i class="fas fa-check me-1"></i>Item Now Back?
                        </button>
                    </div>
                `;
                
                cardDiv.appendChild(cardBodyDiv);
                colDiv.appendChild(cardDiv);
                containerDiv.appendChild(colDiv);
            });
            
            content.innerHTML = '';
            content.appendChild(containerDiv);
            
            // Add event listeners for the new buttons
            content.querySelectorAll('.view-item-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const itemId = this.dataset.itemId;
                    window.location.href = `/item/${itemId}`;
                });
            });
            
            content.querySelectorAll('.push-return-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const loanId = this.dataset.loanId;
                    const itemName = this.dataset.itemName;
                    const borrowerName = this.dataset.borrowerName;
                    pushReturn(loanId, itemName, borrowerName);
                });
            });
        } else {
            const loanCount = result.loans ? result.loans.length : 0;
            countElement.textContent = `My Items Currently on Loan (${loanCount})`;
            content.innerHTML = '<div class="text-center py-4"><i class="fas fa-handshake text-muted mb-3" style="font-size: 3rem;"></i><h6 class="text-muted">No items currently on loan</h6><p class="small text-muted">When someone borrows your items, they\'ll appear here!</p></div>';
        }
    } catch (error) {
        console.error('Error loading active loans:', error);
        const countElement = document.querySelector('#heading3 .animate-target');
        if (countElement) {
            countElement.textContent = 'My Items Currently on Loan (0)';
        }
        const content = document.getElementById('activeLoansContent');
        if (content) {
            content.innerHTML = '<div class="alert alert-danger">Error loading loans</div>';
        }
    }
}

async function loadItemStatuses() {
    const userItems = {{ userItems|json_encode|raw }};
    
    for (const item of userItems) {
        try {
            const response = await fetch(`/api/items/${item.id}/status`);
            const result = await response.json();
            
            const statusElement = document.getElementById(`status-${item.id}`);
            if (statusElement) {
                if (result.isOnLoan) {
                    const statusDisplay = result.statusDisplay || 'On Loan';
                    statusElement.textContent = statusDisplay;
                    
                    if (result.status === 'return_requested') {
                        statusElement.className = 'badge bg-info text-dark';
                        // Add confirmation button for owner
                        const existingBtn = document.getElementById(`confirm-btn-${item.id}`);
                        if (!existingBtn) {
                            const confirmBtn = document.createElement('button');
                            confirmBtn.id = `confirm-btn-${item.id}`;
                            confirmBtn.className = 'btn btn-sm btn-success ms-2';
                            confirmBtn.innerHTML = '<i class="fas fa-check me-1"></i>Confirm Return';
                            confirmBtn.onclick = () => confirmReturn(result.trackingId, item.name);
                            statusElement.parentNode.appendChild(confirmBtn);
                        }
                    } else if (result.status === 'active') {
                        statusElement.className = 'badge bg-warning text-dark';
                    } else {
                        statusElement.className = 'badge bg-secondary text-white';
                    }
                } else {
                    statusElement.textContent = 'Available';
                    statusElement.className = 'badge bg-success';
                }
            }
        } catch (error) {
            console.error(`Error loading status for item ${item.id}:`, error);
            const statusElement = document.getElementById(`status-${item.id}`);
            if (statusElement) {
                statusElement.textContent = 'Available';
                statusElement.className = 'badge bg-success';
            }
        }
    }
}

async function loadActiveLoansCount() {
    try {
        const response = await fetch(`/api/loans/owner/{{ user.id }}`);
        const result = await response.json();
        
        const countElement = document.querySelector('#heading3 .animate-target');
        if (countElement && result.success && result.loans) {
            countElement.textContent = `(${result.loans.length}) My Items: Approved & Out on Loan`;
        }
    } catch (error) {
        console.error('Error loading active loans count:', error);
    }
}

// Global variables for modal state
let currentDashboardLoanId = null;
let currentDashboardItemName = null;
let currentDashboardBorrowerName = null;

// Push Return function for owners to declare item returned - now opens modal
async function pushReturn(loanId, itemName, borrowerName) {
    // Store current loan data for modal use
    currentDashboardLoanId = loanId;
    currentDashboardItemName = itemName;
    currentDashboardBorrowerName = borrowerName || 'Unknown';
    
    // Update modal content
    document.getElementById('dashboardItemName').textContent = itemName;
    document.getElementById('dashboardBorrowerName').textContent = currentDashboardBorrowerName;
    
    // Reset form state
    document.getElementById('dashboardPushReturnConfirm').checked = false;
    document.getElementById('dashboardBorrowerConcerns').checked = false;
    document.getElementById('dashboardConcernsMessageBox').style.display = 'none';
    document.getElementById('dashboardConcernsMessage').value = '';
    updateDashboardReturnButton();
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('dashboardPushReturnModal'));
    modal.show();
}

function toggleDashboardConcernsMessage() {
    const goodConditionCheckbox = document.getElementById('dashboardPushReturnConfirm');
    const concernsCheckbox = document.getElementById('dashboardBorrowerConcerns');
    const messageBox = document.getElementById('dashboardConcernsMessageBox');
    
    // 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('dashboardConcernsMessage').value = '';
    }
    updateDashboardReturnButton();
}

function toggleDashboardGoodCondition() {
    const goodConditionCheckbox = document.getElementById('dashboardPushReturnConfirm');
    const concernsCheckbox = document.getElementById('dashboardBorrowerConcerns');
    const messageBox = document.getElementById('dashboardConcernsMessageBox');
    
    // Radio button behavior - only one can be checked
    if (goodConditionCheckbox.checked) {
        concernsCheckbox.checked = false;
        messageBox.style.display = 'none';
        document.getElementById('dashboardConcernsMessage').value = '';
    }
    updateDashboardReturnButton();
}

function updateDashboardReturnButton() {
    const goodConditionCheckbox = document.getElementById('dashboardPushReturnConfirm');
    const concernsCheckbox = document.getElementById('dashboardBorrowerConcerns');
    const button = document.querySelector('#dashboardPushReturnModal .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 submitDashboardPushReturn() {
    const goodCondition = document.getElementById('dashboardPushReturnConfirm').checked;
    const hasConcerns = document.getElementById('dashboardBorrowerConcerns').checked;
    const concernsMessage = document.getElementById('dashboardConcernsMessage').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;
    }
    
    // Submit push return request
    fetch(`/api/loans/${currentDashboardLoanId}/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('Dashboard push return result:', result);
        if (result.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('dashboardPushReturnModal'));
            if (modal) modal.hide();
            
            // Show success toast
            LocalLendables.showSuccessToast(
                'Return Confirmed!',
                'The item has been marked as returned successfully. The borrower will be notified.'
            );
            
            // Refresh loans and notifications
            loadActiveLoans();
            loadActiveLoansCount();
        } else {
            LocalLendables.showErrorToast(
                'Return Error',
                result.error || 'Unknown error occurred while confirming return.'
            );
        }
    })
    .catch(error => {
        console.error('Error submitting dashboard 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 ? currentUser.id : 'null' }};
    
    fetch(`/api/favorites/${itemId}?userId=${userId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.favorited) {
                heartIcon.style.color = '#ff6b6b';
                button.title = 'Remove from favorites';
            } else {
                heartIcon.style.color = '#ccc';
                button.title = 'Add to favorites';
            }
        } else {
            console.error('Failed to toggle favorite:', data.error);
        }
    })
    .catch(error => {
        console.error('Error toggling favorite:', error);
    });
}

// Handle favorite click with event stopping
function handleFavoriteClick(event, itemId) {
    event.stopPropagation();
    event.preventDefault();
    
    const button = event.currentTarget;
    const heartIcon = button.querySelector('i');
    
    // Toggle favorite status
    toggleFavorite(itemId, button, heartIcon);
    
    return false;
}

// Load initial favorite states for heart icons
function loadInitialFavorites() {
    const userFavorites = {{ userFavorites|json_encode|raw }};
    if (userFavorites && Array.isArray(userFavorites)) {
        const favoriteItemIds = userFavorites.map(fav => fav.id);
        
        // Update heart icons for favorited items
        favoriteItemIds.forEach(itemId => {
            const favoriteBtn = document.querySelector(`[data-item-id="${itemId}"]`);
            if (favoriteBtn) {
                const heartIcon = favoriteBtn.querySelector('i');
                if (heartIcon) {
                    heartIcon.style.color = '#ff6b6b';
                    favoriteBtn.title = 'Remove from favorites';
                }
            }
        });
    }
}

// PERFORMANCE OPTIMIZATION: Image Lazy Loading
document.addEventListener('DOMContentLoaded', function() {
    // Implement lazy loading for better mobile performance
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                const src = img.getAttribute('data-src');
                if (src) {
                    img.src = src;
                    img.removeAttribute('data-src');
                    img.classList.remove('lazy-load');
                    observer.unobserve(img);
                }
            }
        });
    }, {
        rootMargin: '50px 0px' // Start loading 50px before image comes into view
    });

    // Observe all lazy-load images
    document.querySelectorAll('img[data-src]').forEach(img => {
        imageObserver.observe(img);
    });

    // Convert existing images to lazy loading for better performance
    document.querySelectorAll('img[src*="/lendable_items/"]').forEach(img => {
        if (!img.hasAttribute('data-src') && img.src !== '/lendable_items/default-placeholder.jpg') {
            const originalSrc = img.src;
            img.setAttribute('data-src', originalSrc);
            img.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='100'%3E%3Crect width='100%25' height='100%25' fill='%23f8f9fa'/%3E%3Ctext x='50%25' y='50%25' fill='%236c757d' text-anchor='middle' dy='.3em' font-size='14'%3ELoading...%3C/text%3E%3C/svg%3E";
            img.classList.add('lazy-load');
            imageObserver.observe(img);
        }
    });
});

// PERFORMANCE OPTIMIZATION: Debounced API calls
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

console.log('LocalLendables Dashboard v0.88 - Performance optimizations loaded');
</script>

{% endblock %}

{% block styles %}
<style>
.hover-effect-scale:hover {
    transform: scale(1.05);
    transition: transform 0.2s ease;
}

.hover-card {
    transition: all 0.2s ease;
}

.hover-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
}

.hover-card-link:hover {
    text-decoration: none;
}

.hover-card-link:hover .card-title {
    color: #0d6efd !important;
}

.border-dotted {
    border-style: dotted !important;
}

.bg-dotted {
    background-image: radial-gradient(circle, var(--cz-dot-color, #ccc) 1px, transparent 1px);
    background-size: 8px 8px;
}

.animate-underline::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 2px;
    background-color: var(--bs-primary);
    transition: width 0.3s ease;
}

.animate-underline:hover::after {
    width: 100%;
}

.accordion-button {
    position: relative;
}

@media (max-width: 768px) {
    .col {
        padding: 0.25rem;
    }
    
    .accordion-body {
        padding: 0.5rem 0.375rem;
    }
}

/* Reduce accordion spacing globally */
.accordion-item {
    margin-bottom: 0.125rem !important;
}

.accordion-header {
    padding-top: 0.125rem !important;
    padding-bottom: 0.125rem !important;
}

/* Dashboard list link colors */
.accordion-header a:link {
    color: #1a4d1a !important; /* Header background color for unvisited links */
}

.accordion-header a:visited {
    color: black !important; /* Black for visited links */
}

.accordion-header span {
    color: #1a4d1a !important; /* Ensure counters match header color */
}

/* Remove any remaining light blue backgrounds */
.accordion-header {
    background-color: #90EE90 !important; /* Ensure meadow green for all accordion headers */
}

.accordion-button {
    background-color: #90EE90 !important; /* Meadow background for accordion buttons */
}

.accordion-button:not(.collapsed) {
    background-color: #90EE90 !important; /* Keep meadow background when expanded */
}

.accordion-button:focus {
    background-color: #90EE90 !important; /* Keep meadow background on focus */
}

.accordion-button {
    padding-top: 0.375rem !important;
    padding-bottom: 0.375rem !important;
    line-height: 1.2 !important;
}

.accordion-body {
    padding-top: 0.25rem !important;
    padding-bottom: 0.25rem !important;
}

/* Force action button images to display consistently across all browsers - only in dashboard action sections */
.content-wrapper .hover-effect-target[src*="/lendables/logo_"],
.content-wrapper .card-body img[src*="/lendables/logo_"] {
    display: block !important;
    width: 100% !important;
    height: auto !important;
    max-width: 140px !important;
    visibility: visible !important;
    opacity: 1 !important;
    object-fit: contain !important;
    background: transparent !important;
}

/* Ensure action button containers are visible */
.hover-effect-scale {
    display: block !important;
    width: 100% !important;
    text-decoration: none !important;
}

.hover-effect-target {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
}

/* System notification cards - clickable styling */
.system-notification-card {
    transition: all 0.2s ease;
    position: relative;
}

.system-notification-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    border-color: #28a745 !important;
}

.system-notification-card:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

/* Yellow hover effect for "Asking For" items to match Browse page */
.asking-for-item:hover {
    background-color: #fff3cd !important; /* Light yellow background */
    border-color: #ffeaa7 !important; /* Yellow border */
}

.asking-for-item:hover .card-body {
    background-color: transparent !important;
}

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

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

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

/* Force consistent sizing for all Wish List logos */
.wishlist-logo {
    width: 100px !important;
    height: 100px !important;
    object-fit: contain !important;
    border-radius: 50% !important;
    display: inline-block !important;
    max-width: 100px !important;
    max-height: 100px !important;
}
</style>

<!-- Push Return Modal for Dashboard -->
<div class="modal fade" id="dashboardPushReturnModal" tabindex="-1" aria-labelledby="dashboardPushReturnModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="dashboardPushReturnModalLabel">
                    <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>
                
                <div class="mb-3">
                    <h6>Item Details:</h6>
                    <p><strong id="dashboardItemName">Item Name</strong></p>
                    <p>Currently borrowed by: <strong id="dashboardBorrowerName">Borrower Name</strong></p>
                </div>
                
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="dashboardPushReturnConfirm" onchange="toggleDashboardGoodCondition()">
                    <label class="form-check-label" for="dashboardPushReturnConfirm">
                        <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="dashboardBorrowerConcerns" onchange="toggleDashboardConcernsMessage()">
                    <label class="form-check-label" for="dashboardBorrowerConcerns">
                        <strong>I have concerns about the condition of this Item</strong>
                    </label>
                </div>
                
                <div id="dashboardConcernsMessageBox" 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="dashboardConcernsMessage" 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="submitDashboardPushReturn()">
                    <i class="fas fa-check me-1"></i>Confirm Return
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Reminder Form Modal -->
<div class="modal fade" id="reminderModal" tabindex="-1" aria-labelledby="reminderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reminderModalLabel">
                    <i class="fas fa-paper-plane me-2"></i>Send Reminder
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="reminderForm">
                    <input type="hidden" id="reminderNotificationId" name="notificationId">
                    <input type="hidden" id="reminderItemId" name="itemId">
                    
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="fas fa-info-circle me-1"></i>Item Details
                        </label>
                        <div class="alert alert-info" id="reminderItemInfo">
                            Loading item details...
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="reminderMessage" class="form-label">
                            <i class="fas fa-comment me-1"></i>Reminder Message
                        </label>
                        <textarea class="form-control" id="reminderMessage" name="message" rows="3" 
                                  placeholder="Enter your reminder message to the borrower..."
                                  style="font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif !important;">Hi! Just a friendly reminder that your borrowed item is overdue. Please let me know when you can return it. Thanks!</textarea>
                        <div class="form-text">This message will be sent as a notification to the borrower.</div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="sendSMS" name="sendSMS">
                            <label class="form-check-label" for="sendSMS">
                                <i class="fas fa-mobile-alt me-1"></i>Also send SMS text message
                            </label>
                        </div>
                        <div class="form-text text-muted">
                            <i class="fas fa-shield-alt me-1"></i>SMS will only be sent if the borrower has provided a phone number and opted in to SMS notifications
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="markUrgent" name="markUrgent">
                            <label class="form-check-label" for="markUrgent">
                                <i class="fas fa-exclamation-triangle me-1"></i>Mark as urgent reminder
                            </label>
                        </div>
                        <div class="form-text text-muted">Urgent reminders will appear with high priority styling</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="sendReminder()" id="sendReminderBtn">
                    <i class="fas fa-paper-plane me-1"></i>Send Reminder
                </button>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 for Welcome Message -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- FontAwesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<script>
        // Open reminder form modal
        async function openReminderForm(notificationId, itemId, message) {
            try {
                document.getElementById('reminderNotificationId').value = notificationId;
                document.getElementById('reminderItemId').value = itemId;
                
                // Extract item name from message (e.g., 'Item "Electric Push Mower" Overdue! Shall we send a reminder?')
                const itemNameMatch = message.match(/Item "([^"]+)"/);
                const itemName = itemNameMatch ? itemNameMatch[1] : 'Unknown Item';
                
                // Fetch item details
                const response = await fetch(`/api/items/${itemId}`);
                const itemData = await response.json();
                
                // Fetch borrower details
                const loanResponse = await fetch(`/api/items/${itemId}/loan-status`);
                const loanData = await loanResponse.json();
                
                let itemInfo = `<strong>${itemName}</strong>`;
                if (loanData.borrower) {
                    itemInfo += `<br>Currently borrowed by: <strong>${loanData.borrower.showName || loanData.borrower.firstName + ' ' + loanData.borrower.lastName}</strong>`;
                }
                if (loanData.dueDate) {
                    const dueDate = new Date(loanData.dueDate).toLocaleDateString();
                    itemInfo += `<br>Due date: <strong>${dueDate}</strong>`;
                }
                
                document.getElementById('reminderItemInfo').innerHTML = itemInfo;
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('reminderModal'));
                modal.show();
                
            } catch (error) {
                console.error('Error opening reminder form:', error);
                LocalLendables.showToast('Error loading reminder form', 'error');
            }
        }
        
        // Send reminder
        async function sendReminder() {
            try {
                const form = document.getElementById('reminderForm');
                const formData = new FormData(form);
                
                const sendBtn = document.getElementById('sendReminderBtn');
                sendBtn.disabled = true;
                sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Sending...';
                
                const response = await fetch('/api/send-reminder', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Close modal
                    bootstrap.Modal.getInstance(document.getElementById('reminderModal')).hide();
                    
                    // Show success message
                    LocalLendables.showToast('Reminder sent successfully!', 'success');
                    
                    // Dismiss the original notification
                    await dismissNotification(document.getElementById('reminderNotificationId').value);
                    
                } else {
                    LocalLendables.showToast(result.message || 'Failed to send reminder', 'error');
                }
                
            } catch (error) {
                console.error('Error sending reminder:', error);
                LocalLendables.showToast('Error sending reminder', 'error');
            } finally {
                const sendBtn = document.getElementById('sendReminderBtn');
                sendBtn.disabled = false;
                sendBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i>Send Reminder';
            }
        }

        // Mark system notification as read
        async function markSystemNotificationRead(notificationId) {
            try {
                await fetch(`/api/notifications/${notificationId}/mark-read`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                // Refresh the page to update notification state
                window.location.reload();
            } catch (error) {
                console.error('Error marking notification as read:', error);
            }
        }
        
        // Dismiss notification function 
        async function dismissNotification(notificationId) {
            try {
                await fetch(`/api/notifications/${notificationId}/dismiss`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                // Refresh the page to update notification state
                window.location.reload();
            } catch (error) {
                console.error('Error dismissing notification:', error);
            }
        }
        
        // Mark message as read function (for dropdown)
        async function markMessageAsRead(messageId, isSystemNotification) {
            try {
                if (isSystemNotification) {
                    await fetch(`/api/notifications/${messageId}/dismiss`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                } else {
                    await fetch(`/api/messages/${messageId}/mark-read`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                }
                
                // Hide the specific message card
                const messageCard = document.querySelector(`#message-card-${messageId}`);
                if (messageCard) {
                    messageCard.style.display = 'none';
                }
                
                // Check if any messages remain
                const remainingMessages = document.querySelectorAll('#messagesModalBody .card:not([style*="display: none"])');
                if (remainingMessages.length === 0) {
                    document.getElementById('messagesModalBody').innerHTML = '<p class="text-center text-muted">No unread messages</p>';
                }
                
            } catch (error) {
                console.error('Error marking message as read:', error);
            }
        }
</script>
{% endblock %}