<!-- Common Header for All Pages -->
<header class="navbar navbar-expand-lg navbar-dark d-block p-0" style="background-color: #1a4d1a;">
    <div class="container d-block py-2 border-top border-bottom border-dark">
        <!-- Desktop Layout (600px and above) -->
        <div class="row flex-nowrap align-items-center g-0 d-none d-md-flex" style="height: 80px;">
            <div class="col-auto pe-2">
                <!-- Hamburger Menu -->
                <div class="dropdown">
                    <button class="btn btn-link text-white p-1" type="button" id="hamburgerMenu" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-bars" style="font-size: 1.5rem;"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-start" aria-labelledby="hamburgerMenu" style="min-width: 300px; z-index: 99999 !important;">
                        <!-- Alpha Testing - Report a Concern -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-2" href="#" onclick="openAlphaFeedbackModal(); return false;">
                                <div class="rounded-circle bg-danger text-white me-3 d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                                <span class="fw-bold">Report a Concern</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- Back to Dashboard -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-2" href="/dashboard/{{ user.id }}">
                                <img src="/lendables/logo_dashboard_600.png" alt="Dashboard" class="me-3 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                <span>My Dashboard</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- My Lendables Inventory -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-inventory/{{ user.id }}">
                                <img src="/lendables/logo_my_inventory_600.png" alt="My Inventory" class="me-3 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                <span>My Lendables Inventory</span>
                            </a>
                        </li>
                        
                        <!-- My Loan History -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-loan-history/{{ user.id }}">
                                <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                    <i class="fas fa-history"></i>
                                </div>
                                <span>My Loan History</span>
                            </a>
                        </li>
                        
                        <!-- My Messages -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/messages-inbox/{{ user.id }}">
                                <div class="rounded-circle bg-primary text-white me-3 d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-envelope"></i>
                                </div>
                                <span>My Messages</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- My Lendables Actions -->
                        <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                            <img src="/lendables/logo_actions_600.png" alt="Actions" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                            My Lendables Actions:
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-search"></i>
                                </div>
                                <span>Find an Item to Borrow or Lend</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/create-item">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-plus"></i>
                                </div>
                                <span>Create a Lendable Item</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/ask-item">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-heart"></i>
                                </div>
                                <span>Ask for something</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/offer-hour">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <span>Offer Available Hours</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/edit-profile/{{ session.userId ?? currentUser.id }}">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-edit"></i>
                                </div>
                                <span>Edit My Profile</span>
                            </a>
                        </li>

                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- All Listed Lendables -->
                        <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                            <img src="/lendables/logo_browse_600.png" alt="Browse" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                            Browse All Lendables
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-random"></i>
                                </div>
                                <span>All Items, Random Browse</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse?sort=alphabetic">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-sort-alpha-down"></i>
                                </div>
                                <span>All Items, Listed Alphabetically</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse-hours">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <span>Browse Offered Hours</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- Our Local Lendables -->
                        <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                            <img src="/lendables/logo_community_300.png" alt="Community" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                            Our Local Lendables
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/about-community">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-users"></i>
                                </div>
                                <span>About Our Community</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/our-manager">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <span>Our Manager</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/how-supported" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-life-ring"></i>
                                </div>
                                <span>How Lendables is Supported</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/invite-member">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-plus"></i>
                                </div>
                                <span>How to Invite a new Member</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/handshake-agreement">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-handshake"></i>
                                </div>
                                <span>View Lendable Handshake Agreement</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- General Local Lendables -->
                        <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                            <img src="/lendables/logo_mondo.png" alt="Mondo" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                            General Local Lendables
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html#whatareyou" target="_blank">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-question"></i>
                                </div>
                                <span>What are we?</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html#nonprofit" target="_blank">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-balance-scale"></i>
                                </div>
                                <span>Our Ethical Business Model</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html" target="_blank">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-question-circle"></i>
                                </div>
                                <span>Frequently Asked Questions</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/dashboard/{{ currentUser.id }}">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-play"></i>
                                </div>
                                <span>Local Lendables Demo</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="col col-lg-3 d-flex align-items-center">
                <a href="/dashboard/{{ user.id }}" class="navbar-brand me-0 onlycavolini d-flex align-items-center">
                    <img src="/local_circle_logo.png" 
                         class="img-fluid me-2" 
                         height="76" 
                         width="76"
                         alt="Local Lendables Logo">
                    <span class="headertitle text-white" style="line-height: 100%;">Local Lendables<br>&nbsp;&nbsp;Demo</span>
                </a>
            </div>
            <div class="col col-lg-9 d-flex align-items-center justify-content-end">
                <div class="position-relative d-block pe-1 pe-lg-2" style="min-width: 200px;">
                    <input type="search" 
                           id="headerSearchInput"
                           class="form-control form-control-sm border-white rounded-pill" 
                           placeholder="    Search Lendables"
                           autocomplete="off"
                           style="padding-left: 35px; width: 100%;">
                    <i class="fas fa-search position-absolute text-muted" style="left: 12px; top: 50%; transform: translateY(-50%);"></i>
                    <div id="searchResults" class="position-fixed bg-white border rounded shadow-lg mt-1" style="z-index: 1050; max-height: 400px; overflow-y: auto; overflow-x: hidden; display: none; width: 50vw; left: 25vw; top: 72px; padding: 8px;"></div>
                </div>
                <div class="d-flex align-items-center">
                    <!-- Messages Notification -->
                    <div class="me-3">
                        {% if hasUnreadNotifications %}
                        <a href="/messages-inbox/{{ user.id }}" class="btn btn-sm" style="background-color: #dc3545; border: none; color: white;" title="My Messages" data-bs-toggle="tooltip" data-bs-placement="bottom">
                            <i class="fas fa-envelope"></i>
                        </a>
                        {% else %}
                        <a href="/messages-inbox/{{ user.id }}" class="btn btn-sm" style="background-color: transparent; border: none; color: white;" title="My Messages" data-bs-toggle="tooltip" data-bs-placement="bottom">
                            <i class="fas fa-envelope"></i>
                        </a>
                        {% endif %}
                    </div>
                    
                    <!-- User Profile Dropdown -->
                    <div class="dropdown me-3">
                        <button class="btn btn-link text-white p-0 d-flex align-items-center" type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            {% if user.avatar %}
                                <img src="/ll_images/{{ user.avatar }}" 
                                     alt="{% if user.showName %}{{ user.showName }}{% else %}{{ user.firstName }}{% endif %}" 
                                     class="rounded-circle me-2" 
                                     width="48" 
                                     height="48"
                                     style="object-fit: cover; border: 2px solid #28a745;"
                                     onerror="this.src='/avatars/default.svg'; this.style.display='none'; this.nextElementSibling.style.display='inline';">
                                <i class="fas fa-user-circle text-white me-2" style="font-size: 3rem; display: none;"></i>
                            {% else %}
                                <i class="fas fa-user-circle text-white me-2" style="font-size: 3rem;"></i>
                            {% endif %}
                            <span class="text-white small d-none d-lg-inline">{% if user.showName %}{{ user.showName }}{% else %}{{ user.firstName }}{% endif %}</span>
                            <i class="fas fa-chevron-down text-white ms-1"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown" style="z-index: 99999 !important;">
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/profile/{{ user.id }}">
                                    <i class="fas fa-user me-2"></i>
                                    My Profile
                                </a>
                            </li>
                            {% if user.roles and 'ROLE_ADMIN' in user.roles %}
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/admin/dashboard">
                                    <i class="fas fa-shield-alt me-2 text-danger"></i>
                                    <span class="text-danger fw-bold">Admin Dashboard</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/admin/alpha-feedback">
                                    <i class="fas fa-exclamation-triangle me-2 text-warning"></i>
                                    <span class="text-warning fw-bold">Alpha Feedback</span>
                                </a>
                            </li>

                            {% endif %}
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/my-spreadsheet/{{ user.id }}">
                                    <i class="fas fa-table me-2"></i>
                                    My Spreadsheet
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/my-loan-history/{{ user.id }}">
                                    <i class="fas fa-history me-2"></i>
                                    My Loan History
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/edit-profile/{{ user.id }}">
                                    <i class="fas fa-user-edit me-2"></i>
                                    Edit Profile
                                </a>
                            </li>

                        </ul>
                    </div>
                    <button class="btn btn-sm px-2" onclick="performLogout()" title="Logout" style="background-color: white; border: 1px solid #dc3545;">
                        <i class="fas fa-power-off text-danger"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Mobile Layout (under 600px) -->
        <div class="d-block d-md-none">
            <!-- First Row: Hamburger + Logo + Avatar -->
            <div class="row align-items-center g-0 py-2">
                <div class="col-auto pe-2">
                    <!-- Hamburger Menu -->
                    <div class="dropdown">
                        <button class="btn btn-link text-white p-1" type="button" id="hamburgerMenuMobile" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-bars" style="font-size: 1.3rem;"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-start" aria-labelledby="hamburgerMenuMobile" style="min-width: 300px; z-index: 99999 !important;">
                            <!-- Alpha Testing - Report a Concern -->
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-2" href="#" onclick="openAlphaFeedbackModal(); return false;">
                                    <div class="rounded-circle bg-danger text-white me-3 d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-exclamation-triangle"></i>
                                    </div>
                                    <span class="fw-bold">Report a Concern</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- Back to Dashboard -->
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-2" href="/dashboard/{{ user.id }}">
                                    <img src="/lendables/logo_dashboard_600.png" alt="Dashboard" class="me-3 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                    <span>My Dashboard</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- My Lendables Inventory -->
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/my-inventory/{{ user.id }}">
                                    <img src="/lendables/logo_my_inventory_600.png" alt="My Inventory" class="me-3 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                    <span>My Lendables Inventory</span>
                                </a>
                            </li>
                            
                            <!-- My Loan History -->
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/my-loan-history/{{ user.id }}">
                                    <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                        <i class="fas fa-history"></i>
                                    </div>
                                    <span>My Loan History</span>
                                </a>
                            </li>
                            
                            <!-- My Messages -->
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/messages-inbox/{{ user.id }}">
                                    <div class="rounded-circle bg-primary text-white me-3 d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-envelope"></i>
                                    </div>
                                    <span>My Messages</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- My Lendables Actions -->
                            <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                                <img src="/lendables/logo_actions_600.png" alt="Actions" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                My Lendables Actions:
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                    <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-search"></i>
                                    </div>
                                    <span>Find an Item to Borrow or Lend</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/create-item">
                                    <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-plus"></i>
                                    </div>
                                    <span>Create a Lendable Item</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/ask-item">
                                    <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-heart"></i>
                                    </div>
                                    <span>Ask for something</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/offer-hour">
                                    <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <span>Offer Available Hours</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/edit-profile/{{ session.userId ?? currentUser.id }}">
                                    <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-user-edit"></i>
                                    </div>
                                    <span>Edit My Profile</span>
                                </a>
                            </li>

                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- All Listed Lendables -->
                            <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                                <img src="/lendables/logo_browse_600.png" alt="Browse" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                Browse All Lendables
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                    <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-random"></i>
                                    </div>
                                    <span>All Items, Random Browse</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/browse?sort=alphabetic">
                                    <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-sort-alpha-down"></i>
                                    </div>
                                    <span>All Items, Listed Alphabetically</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/browse-hours">
                                    <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <span>Browse Offered Hours</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- Our Local Lendables -->
                            <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                                <img src="/lendables/logo_community_300.png" alt="Community" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                Our Local Lendables
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/about-community">
                                    <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <span>About Our Community</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/our-manager">
                                    <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-user-tie"></i>
                                    </div>
                                    <span>Our Manager</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/how-supported" style="text-decoration: line-through;">
                                    <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-life-ring"></i>
                                    </div>
                                    <span>How Lendables is Supported</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/invite-member">
                                    <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-user-plus"></i>
                                    </div>
                                    <span>How to Invite a new Member</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/handshake-agreement">
                                    <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-handshake"></i>
                                    </div>
                                    <span>View Lendable Handshake Agreement</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            
                            <!-- General Local Lendables -->
                            <li class="dropdown-header fw-bold d-flex align-items-center py-1">
                                <img src="/lendables/logo_mondo.png" alt="Mondo" class="me-2 rounded-circle" style="width: 48px; height: 48px; object-fit: cover;">
                                General Local Lendables
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html#whatareyou" target="_blank">
                                    <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-question"></i>
                                    </div>
                                    <span>What are we?</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html#nonprofit" target="_blank">
                                    <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-balance-scale"></i>
                                    </div>
                                    <span>Our Ethical Business Model</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="https://locallendables.com/faq.html" target="_blank">
                                    <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-question-circle"></i>
                                    </div>
                                    <span>Frequently Asked Questions</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center py-1" href="/dashboard/{{ currentUser.id }}">
                                    <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-play"></i>
                                    </div>
                                    <span>Local Lendables Demo</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="col d-flex align-items-center justify-content-center">
                    <a href="/dashboard/{{ user.id }}" class="navbar-brand me-0 onlycavolini d-flex align-items-center text-decoration-none">
                        <img src="/local_circle_logo.png" 
                             class="img-fluid me-2" 
                             height="56" 
                             width="56"
                             alt="Local Lendables Logo">
                        <span class="headertitle text-white" style="line-height: 100%; font-size: 0.9rem;">Local Lendables<br>&nbsp;&nbsp;Demo</span>
                    </a>
                </div>
                <div class="col-auto ps-2">
                    <!-- User Profile Dropdown -->
                    <div class="dropdown">
                        <button class="btn btn-link text-white p-0 d-flex align-items-center" type="button" id="userDropdownMobile" data-bs-toggle="dropdown" aria-expanded="false">
                            {% if user.avatar %}
                                <img src="/ll_images/{{ user.avatar }}" 
                                     alt="{% if user.showName %}{{ user.showName|slice(0,10) }}{% else %}{{ user.firstName|slice(0,10) }}{% endif %}" 
                                     class="rounded-circle" 
                                     width="36" 
                                     height="36"
                                     style="object-fit: cover; border: 2px solid #28a745;"
                                     onerror="this.src='/avatars/default.svg'; this.style.display='none'; this.nextElementSibling.style.display='inline';">
                                <i class="fas fa-user-circle text-white" style="font-size: 2rem; display: none;"></i>
                            {% else %}
                                <i class="fas fa-user-circle text-white" style="font-size: 2rem;"></i>
                            {% endif %}
                            <i class="fas fa-chevron-down text-white ms-1" style="font-size: 0.6rem;"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdownMobile" style="z-index: 99999 !important;">
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/profile/{{ user.id }}">
                                    <i class="fas fa-user me-2"></i>
                                    My Profile
                                </a>
                            </li>
                            {% if user.roles and 'ROLE_ADMIN' in user.roles %}
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/admin/dashboard">
                                    <i class="fas fa-shield-alt me-2 text-danger"></i>
                                    <span class="text-danger fw-bold">Admin Dashboard</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/admin/alpha-feedback">
                                    <i class="fas fa-exclamation-triangle me-2 text-warning"></i>
                                    <span class="text-warning fw-bold">Alpha Feedback</span>
                                </a>
                            </li>
                            {% endif %}
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/my-spreadsheet/{{ user.id }}">
                                    <i class="fas fa-table me-2"></i>
                                    My Spreadsheet
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/my-loan-history/{{ user.id }}">
                                    <i class="fas fa-history me-2"></i>
                                    My Loan History
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/edit-profile/{{ user.id }}">
                                    <i class="fas fa-user-edit me-2"></i>
                                    Edit Profile
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <!-- Second Row: Search Form and Messages/Logout -->
            <div class="row g-0 pb-2 align-items-center">
                <div class="col-7">
                    <div class="position-relative">
                        <input type="search" 
                               id="headerSearchInputMobile"
                               class="form-control form-control-sm border-white rounded-pill" 
                               placeholder="  Search"
                               autocomplete="off"
                               style="padding-left: 28px; width: 100%; font-size: 0.8rem;">
                        <i class="fas fa-search position-absolute text-muted" style="left: 8px; top: 50%; transform: translateY(-50%); font-size: 0.7rem;"></i>
                        <div id="searchResultsMobile" class="position-fixed bg-white border rounded shadow-lg mt-1" style="z-index: 1050; max-height: 400px; overflow-y: auto; overflow-x: hidden; display: none; width: 90vw; left: 5vw; top: 120px; padding: 8px;"></div>
                    </div>
                </div>
                <div class="col-5 d-flex align-items-center justify-content-end">
                    <!-- Messages Notification -->
                    <div class="me-2">
                        {% if hasUnreadNotifications %}
                        <a href="/messages-inbox/{{ user.id }}" class="btn btn-sm" style="background-color: #dc3545; border: none; color: white; padding: 4px 8px;" title="My Messages">
                            <i class="fas fa-envelope" style="font-size: 0.8rem;"></i>
                        </a>
                        {% else %}
                        <a href="/messages-inbox/{{ user.id }}" class="btn btn-sm" style="background-color: transparent; border: none; color: white; padding: 4px 8px;" title="My Messages">
                            <i class="fas fa-envelope" style="font-size: 0.8rem;"></i>
                        </a>
                        {% endif %}
                    </div>
                    
                    <!-- Logout Button -->
                    <button class="btn btn-sm px-2" onclick="performLogout()" title="Logout" style="background-color: white; border: 1px solid #dc3545; padding: 4px 8px;">
                        <i class="fas fa-power-off text-danger" style="font-size: 0.8rem;"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Alpha Testing Feedback Modal -->
<div class="modal fade" id="alphaFeedbackModal" tabindex="-1" aria-labelledby="alphaFeedbackModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="alphaFeedbackModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>Report a Concern - Alpha Testing
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="alphaFeedbackForm">
                    <div class="row mb-3">
                        <div class="col-md-3 text-center">
                            <div class="mb-2">
                                <img id="alphaUserAvatar" src="/ll_images/{{ user.avatar|default('na1.jpg') }}" 
                                     class="rounded-circle border border-3 border-success" 
                                     style="width: 80px; height: 80px; object-fit: cover;" alt="Your Avatar">
                            </div>
                            <small class="text-muted">{{ user.showName|default(user.firstName ~ ' ' ~ user.lastName) }}</small>
                        </div>
                        <div class="col-md-9">
                            <label for="testerComments" class="form-label fw-bold">What concern would you like to report?</label>
                            <textarea class="form-control" id="testerComments" name="testerComments" rows="4" 
                                      placeholder="Please describe what you've encountered, what you expected to happen, or any suggestions you have..."></textarea>
                            
                            <!-- Screenshot Preview (above the add screenshots section) -->
                            <div id="screenshotPreview" class="mt-2 d-flex gap-2 flex-wrap"></div>
                            
                            <!-- Screenshot Paste Section -->
                            <div class="mt-3">
                                <label class="form-label small">
                                    <strong>Add Screenshots (Optional)</strong> - Up to 3 images
                                </label>
                                <div id="pasteArea" class="border rounded p-2 text-center" style="background-color: #f8f9fa; border-style: dashed !important;">
                                    <i class="fas fa-clipboard me-1 text-muted" style="font-size: 0.9rem;"></i>
                                    <span class="text-muted small">Press <kbd style="font-size: 0.75rem;">Ctrl+V</kbd> or right-click to paste</span>
                                    <div class="mt-1">
                                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="document.getElementById('screenshotUpload').click()" style="font-size: 0.75rem; padding: 2px 8px;">
                                            <i class="fas fa-upload me-1"></i>Browse files
                                        </button>
                                        <input type="file" class="d-none" id="screenshotUpload" name="screenshots" 
                                               accept="image/*" multiple>
                                    </div>
                                </div>
                                <div class="form-text small">Images resized to 400px automatically</div>
                            </div>
                            
                            <div class="form-text mt-2 small">
                                Your feedback helps improve LocalLendables. We'll capture page information automatically.
                            </div>
                        </div>
                    </div>
                    
                    <!-- Visual Context Display (Admin/Manager Only) -->
                    {% if user and user.roles and ('ROLE_ADMIN' in user.roles or 'ROLE_MANAGER' in user.roles) %}
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card bg-light border-info">
                                <div class="card-header d-flex justify-content-between align-items-center bg-info text-white">
                                    <h6 class="mb-0"><i class="fas fa-desktop me-2"></i>Page Context Information <span class="badge bg-light text-info ms-2">Admin</span></h6>
                                    <button type="button" class="btn btn-sm btn-outline-light" onclick="toggleContextDetails()">
                                        <span id="contextToggleText">Show Details</span>
                                        <i class="fas fa-chevron-down" id="contextToggleIcon"></i>
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <small class="text-muted">Page:</small>
                                            <div id="displayPageTitle" class="fw-bold">Loading...</div>
                                        </div>
                                        <div class="col-md-6">
                                            <small class="text-muted">URL:</small>
                                            <div id="displayCurrentUrl" class="small text-truncate">Loading...</div>
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-md-6">
                                            <small class="text-muted">Viewport:</small>
                                            <div id="displayViewport" class="small">Loading...</div>
                                        </div>
                                        <div class="col-md-6">
                                            <small class="text-muted">Timestamp:</small>
                                            <div id="displayTimestamp" class="small">Loading...</div>
                                        </div>
                                    </div>
                                    
                                    <!-- Detailed Context (Hidden by default) -->
                                    <div id="contextDetails" class="mt-3" style="display: none;">
                                        <hr>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="small fw-bold">Visible Interactive Elements:</h6>
                                                <div id="displayVisibleElements" class="small"></div>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="small fw-bold">Errors/Warnings:</h6>
                                                <div id="displayErrors" class="small"></div>
                                            </div>
                                        </div>
                                        <div class="mt-2">
                                            <h6 class="small fw-bold">Browser Info:</h6>
                                            <div id="displayBrowserInfo" class="small"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endif %}
                    
                    <!-- Hidden fields for automatic data collection -->
                    <input type="hidden" id="pageTitle" name="pageTitle" value="">
                    <input type="hidden" id="previousPage" name="previousPage" value="">
                    <input type="hidden" id="currentUrl" name="currentUrl" value="">
                    <input type="hidden" id="userAgent" name="userAgent" value="">
                    <input type="hidden" id="browserInfo" name="browserInfo" value="">
                    <input type="hidden" id="sessionData" name="sessionData" value="">
                </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-danger" onclick="submitAlphaFeedback()">
                    <i class="fas fa-paper-plane me-1"></i>Submit Concern
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function openAlphaFeedbackModal() {
    // Collect automatic data
    document.getElementById('pageTitle').value = document.title;
    document.getElementById('previousPage').value = document.referrer || 'Direct/Unknown';
    document.getElementById('currentUrl').value = window.location.href;
    document.getElementById('userAgent').value = navigator.userAgent;
    
    // Collect browser info
    const browserInfo = {
        language: navigator.language,
        platform: navigator.platform,
        cookieEnabled: navigator.cookieEnabled,
        screenWidth: screen.width,
        screenHeight: screen.height,
        viewportWidth: window.innerWidth,
        viewportHeight: window.innerHeight,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
    };
    document.getElementById('browserInfo').value = JSON.stringify(browserInfo);
    
    // Collect enhanced session data with visual context
    const visualContext = captureVisualContext();
    const sessionData = {
        timestamp: new Date().toISOString(),
        viewport: {
            width: window.innerWidth,
            height: window.innerHeight
        },
        screen: {
            width: screen.width,
            height: screen.height
        },
        scroll: {
            x: window.scrollX,
            y: window.scrollY
        },
        visualContext: visualContext,
        sessionStorage: Object.keys(sessionStorage).length,
        localStorage: Object.keys(localStorage).length
    };
    document.getElementById('sessionData').value = JSON.stringify(sessionData);
    
    // Update display elements
    updateContextDisplay(sessionData, browserInfo, visualContext);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('alphaFeedbackModal'));
    modal.show();
}

function updateContextDisplay(sessionData, browserInfo, visualContext) {
    // Only update if elements exist (admin users only)
    const displayPageTitle = document.getElementById('displayPageTitle');
    const displayCurrentUrl = document.getElementById('displayCurrentUrl');
    const displayViewport = document.getElementById('displayViewport');
    const displayTimestamp = document.getElementById('displayTimestamp');
    const elementsDiv = document.getElementById('displayVisibleElements');
    
    if (!displayPageTitle) return; // Not an admin user, skip display updates
    
    // Update basic information
    displayPageTitle.textContent = document.title;
    displayCurrentUrl.textContent = window.location.href;
    displayViewport.textContent = `${sessionData.viewport.width} × ${sessionData.viewport.height}`;
    displayTimestamp.textContent = new Date().toLocaleString();
    // Update visible elements (only if element exists)
    if (elementsDiv) {
        if (visualContext.pageStructure && visualContext.pageStructure.visibleElements) {
            const elements = visualContext.pageStructure.visibleElements.slice(0, 5);
            elementsDiv.innerHTML = elements.length > 0 
                ? elements.map(el => `<div class="mb-1"><strong>${el.tag.toUpperCase()}</strong> ${el.text ? `"${el.text.substring(0, 30)}..."` : ''}</div>`).join('')
                : '<div class="text-muted">No interactive elements detected</div>';
        } else {
            elementsDiv.innerHTML = '<div class="text-muted">Context capture in progress...</div>';
        }
    }
    
    // Update errors (only if element exists)
    const errorsDiv = document.getElementById('displayErrors');
    if (errorsDiv) {
        if (visualContext.pageStructure && visualContext.pageStructure.errors) {
            const errors = visualContext.pageStructure.errors;
            errorsDiv.innerHTML = errors.length > 0 
                ? errors.map(err => `<div class="text-danger small">${err.text.substring(0, 50)}...</div>`).join('')
                : '<div class="text-success">No errors detected</div>';
        } else {
            errorsDiv.innerHTML = '<div class="text-muted">Checking for errors...</div>';
        }
    }
    
    // Update browser info (only if element exists)
    const browserDiv = document.getElementById('displayBrowserInfo');
    if (browserDiv) {
        browserDiv.innerHTML = `
            <div><strong>Browser:</strong> ${navigator.userAgent.substring(0, 50)}...</div>
            <div><strong>Platform:</strong> ${browserInfo.platform}</div>
            <div><strong>Screen:</strong> ${browserInfo.screenWidth} × ${browserInfo.screenHeight}</div>
        `;
    }
}

function toggleContextDetails() {
    const details = document.getElementById('contextDetails');
    const toggleText = document.getElementById('contextToggleText');
    const toggleIcon = document.getElementById('contextToggleIcon');
    
    if (details.style.display === 'none') {
        details.style.display = 'block';
        toggleText.textContent = 'Hide Details';
        toggleIcon.className = 'fas fa-chevron-up';
    } else {
        details.style.display = 'none';
        toggleText.textContent = 'Show Details';
        toggleIcon.className = 'fas fa-chevron-down';
    }
}

// Handle screenshot paste and preview
document.addEventListener('DOMContentLoaded', function() {
    const screenshotUpload = document.getElementById('screenshotUpload');
    const screenshotPreview = document.getElementById('screenshotPreview');
    let pastedImages = []; // Store pasted images
    
    // Handle file upload (fallback option)
    if (screenshotUpload) {
        screenshotUpload.addEventListener('change', function(e) {
            const files = Array.from(e.target.files).slice(0, 3); // Limit to 3 files
            updateScreenshotPreview(files);
        });
    }
    
    // Handle clipboard paste for screenshots
    function handlePasteEvent(e) {
        // Only handle paste when the feedback modal is open
        const modal = document.getElementById('alphaFeedbackModal');
        if (!modal || !modal.classList.contains('show')) {
            return;
        }
        
        const items = e.clipboardData.items;
        const imageFiles = [];
        
        for (let item of items) {
            if (item.type.indexOf('image') !== -1) {
                const file = item.getAsFile();
                if (file) {
                    imageFiles.push(file);
                }
            }
        }
        
        if (imageFiles.length > 0) {
            e.preventDefault();
            
            // Limit total images to 3 (combining pasted and uploaded)
            const currentImageCount = pastedImages.length + (screenshotUpload.files ? screenshotUpload.files.length : 0);
            const availableSlots = 3 - currentImageCount;
            const imagesToAdd = imageFiles.slice(0, availableSlots);
            
            if (imagesToAdd.length > 0) {
                pastedImages = pastedImages.concat(imagesToAdd);
                updateScreenshotPreview();
                
                // Show feedback
                const feedback = document.createElement('div');
                feedback.className = 'alert alert-success alert-dismissible fade show mt-2';
                feedback.innerHTML = `
                    <i class="fas fa-check me-2"></i>
                    ${imagesToAdd.length} screenshot${imagesToAdd.length > 1 ? 's' : ''} pasted successfully!
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                screenshotPreview.parentNode.insertBefore(feedback, screenshotPreview);
                
                // Auto-remove feedback after 3 seconds
                setTimeout(() => {
                    if (feedback.parentNode) {
                        feedback.parentNode.removeChild(feedback);
                    }
                }, 3000);
            }
        }
    }
    
    // Standard paste event
    document.addEventListener('paste', handlePasteEvent);
    
    // Right-click context menu with paste option
    const pasteArea = document.getElementById('pasteArea');
    if (pasteArea) {
        pasteArea.addEventListener('contextmenu', function(e) {
            const modal = document.getElementById('alphaFeedbackModal');
            if (!modal || !modal.classList.contains('show')) {
                return;
            }
            
            e.preventDefault();
            
            // Create custom context menu
            const contextMenu = document.createElement('div');
            contextMenu.className = 'position-absolute bg-white border rounded shadow-sm';
            contextMenu.style.cssText = `
                left: ${e.pageX}px;
                top: ${e.pageY}px;
                z-index: 10000;
                padding: 8px 0;
                min-width: 120px;
                border: 1px solid #dee2e6;
            `;
            
            contextMenu.innerHTML = `
                <div class="px-3 py-2 hover-bg-light" style="cursor: pointer; user-select: none;" onclick="triggerPaste()">
                    <i class="fas fa-clipboard me-2"></i>Paste
                </div>
            `;
            
            document.body.appendChild(contextMenu);
            
            // Remove context menu when clicking elsewhere
            const removeContextMenu = (event) => {
                if (!contextMenu.contains(event.target)) {
                    document.body.removeChild(contextMenu);
                    document.removeEventListener('click', removeContextMenu);
                }
            };
            
            setTimeout(() => {
                document.addEventListener('click', removeContextMenu);
            }, 10);
            
            // Add hover effect
            contextMenu.querySelector('.hover-bg-light').addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f8f9fa';
            });
            contextMenu.querySelector('.hover-bg-light').addEventListener('mouseleave', function() {
                this.style.backgroundColor = 'transparent';
            });
        });
    }
    
    // Function to trigger paste programmatically
    window.triggerPaste = async function() {
        try {
            if (navigator.clipboard && navigator.clipboard.read) {
                const clipboardItems = await navigator.clipboard.read();
                const imageFiles = [];
                
                for (const clipboardItem of clipboardItems) {
                    for (const type of clipboardItem.types) {
                        if (type.startsWith('image/')) {
                            const blob = await clipboardItem.getType(type);
                            const file = new File([blob], `pasted-image.${type.split('/')[1]}`, { type });
                            imageFiles.push(file);
                        }
                    }
                }
                
                if (imageFiles.length > 0) {
                    // Simulate paste event
                    const pasteEvent = new ClipboardEvent('paste', {
                        clipboardData: new DataTransfer()
                    });
                    
                    // Add files to clipboard data
                    imageFiles.forEach(file => {
                        pasteEvent.clipboardData.items.add(file);
                    });
                    
                    handlePasteEvent(pasteEvent);
                } else {
                    // Fallback: show message if no images in clipboard
                    const feedback = document.createElement('div');
                    feedback.className = 'alert alert-warning alert-dismissible fade show mt-2';
                    feedback.innerHTML = `
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        No images found in clipboard. Copy a screenshot first.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    screenshotPreview.parentNode.insertBefore(feedback, screenshotPreview);
                    
                    setTimeout(() => {
                        if (feedback.parentNode) {
                            feedback.parentNode.removeChild(feedback);
                        }
                    }, 3000);
                }
            } else {
                // Fallback for browsers without clipboard API
                const feedback = document.createElement('div');
                feedback.className = 'alert alert-info alert-dismissible fade show mt-2';
                feedback.innerHTML = `
                    <i class="fas fa-info-circle me-2"></i>
                    Use Ctrl+V (or Cmd+V) to paste screenshots
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                screenshotPreview.parentNode.insertBefore(feedback, screenshotPreview);
                
                setTimeout(() => {
                    if (feedback.parentNode) {
                        feedback.parentNode.removeChild(feedback);
                    }
                }, 3000);
            }
        } catch (error) {
            console.error('Paste operation failed:', error);
            // Show fallback message
            const feedback = document.createElement('div');
            feedback.className = 'alert alert-info alert-dismissible fade show mt-2';
            feedback.innerHTML = `
                <i class="fas fa-info-circle me-2"></i>
                Use Ctrl+V (or Cmd+V) to paste screenshots
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            screenshotPreview.parentNode.insertBefore(feedback, screenshotPreview);
            
            setTimeout(() => {
                if (feedback.parentNode) {
                    feedback.parentNode.removeChild(feedback);
                }
            }, 3000);
        }
    };
    
    function updateScreenshotPreview(uploadedFiles = null) {
        screenshotPreview.innerHTML = '';
        
        // Combine uploaded files and pasted images
        const allImages = [];
        
        if (uploadedFiles) {
            allImages.push(...uploadedFiles);
        } else if (screenshotUpload.files) {
            allImages.push(...Array.from(screenshotUpload.files));
        }
        
        allImages.push(...pastedImages);
        
        // Limit to 3 total images
        const imagesToShow = allImages.slice(0, 3);
        
        imagesToShow.forEach((file, index) => {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const imgContainer = document.createElement('div');
                    imgContainer.className = 'position-relative';
                    imgContainer.innerHTML = `
                        <img src="${e.target.result}" 
                             style="width: 120px; height: 80px; object-fit: cover; border: 1px solid #ddd; border-radius: 4px;" 
                             title="Screenshot ${index + 1}: ${file.name || 'Pasted image'}">
                        <small class="position-absolute bottom-0 start-0 bg-dark text-white px-1 rounded-end" style="font-size: 10px;">
                            ${index + 1}
                        </small>
                        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 rounded-circle" 
                                style="width: 20px; height: 20px; font-size: 10px; line-height: 1;" 
                                onclick="removeScreenshot(${index})" title="Remove">
                            ×
                        </button>
                    `;
                    screenshotPreview.appendChild(imgContainer);
                };
                reader.readAsDataURL(file);
            }
        });
    }
    
    // Global function to remove screenshots
    window.removeScreenshot = function(index) {
        const uploadedCount = screenshotUpload.files ? screenshotUpload.files.length : 0;
        
        if (index < uploadedCount) {
            // Remove from uploaded files
            const dt = new DataTransfer();
            Array.from(screenshotUpload.files).forEach((file, i) => {
                if (i !== index) dt.items.add(file);
            });
            screenshotUpload.files = dt.files;
        } else {
            // Remove from pasted images
            const pastedIndex = index - uploadedCount;
            pastedImages.splice(pastedIndex, 1);
        }
        
        updateScreenshotPreview();
    };
    
    // Reset pasted images when modal closes
    document.getElementById('alphaFeedbackModal').addEventListener('hidden.bs.modal', function() {
        pastedImages = [];
        if (screenshotUpload) {
            screenshotUpload.value = '';
        }
        screenshotPreview.innerHTML = '';
    });
    
    // Make pasted images available globally for form submission
    window.getPastedImages = function() {
        return pastedImages;
    };
});

async function submitAlphaFeedback() {
    const form = document.getElementById('alphaFeedbackForm');
    const comments = document.getElementById('testerComments').value.trim();
    
    if (!comments) {
        alert('Please enter your concern or feedback before submitting.');
        return;
    }
    
    try {
        // Create FormData for file uploads
        const formData = new FormData();
        formData.append('testerComments', comments);
        formData.append('pageTitle', document.getElementById('pageTitle').value);
        formData.append('previousPage', document.getElementById('previousPage').value);
        formData.append('currentUrl', document.getElementById('currentUrl').value);
        formData.append('userAgent', document.getElementById('userAgent').value);
        formData.append('browserInfo', document.getElementById('browserInfo').value);
        formData.append('sessionData', document.getElementById('sessionData').value);
        
        // Add screenshot files (both uploaded and pasted)
        const screenshotFiles = document.getElementById('screenshotUpload').files;
        let imageCount = 0;
        
        // Add uploaded files
        for (let i = 0; i < Math.min(screenshotFiles.length, 3); i++) {
            formData.append('screenshots', screenshotFiles[i]);
            imageCount++;
        }
        
        // Add pasted images using global function
        const pastedImages = window.getPastedImages ? window.getPastedImages() : [];
        if (pastedImages && pastedImages.length > 0) {
            console.log('Adding pasted images:', pastedImages.length);
            for (let i = 0; i < Math.min(pastedImages.length, 3 - imageCount); i++) {
                formData.append('screenshots', pastedImages[i]);
                imageCount++;
            }
        }
        
        console.log('Total images being submitted:', imageCount);
        
        // Show loading indicator
        const submitBtn = document.querySelector('#alphaFeedbackModal .btn-danger');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Submitting...';
        submitBtn.disabled = true;
        
        const response = await fetch('/api/alpha-feedback', {
            method: 'POST',
            body: formData // Don't set Content-Type header for FormData
        });
        
        if (response.ok) {
            // Close modal and show success
            const modal = bootstrap.Modal.getInstance(document.getElementById('alphaFeedbackModal'));
            modal.hide();
            
            // Reset form
            form.reset();
            
            // Show Bootstrap-styled success message
            showBootstrapAlert('Thank you for your feedback!', 'Your concern has been submitted and will be reviewed by our team.', 'success');
        } else {
            const error = await response.text();
            showBootstrapAlert('Submission Error', 'Error submitting feedback: ' + error, 'danger');
        }
    } catch (error) {
        console.error('Error submitting alpha feedback:', error);
        showBootstrapAlert('Connection Error', 'Error submitting feedback. Please try again.', 'danger');
    }
}

function captureVisualContext() {
    try {
        const visibleElements = [];
        const interactiveSelectors = ['button', 'a', 'input', 'select', 'textarea', '[role="button"]', '[onclick]', '.dropdown-item', '.btn'];
        const elements = document.querySelectorAll(interactiveSelectors.join(', '));
        
        elements.forEach(el => {
            const rect = el.getBoundingClientRect();
            if (rect.top >= 0 && rect.top <= window.innerHeight && 
                rect.left >= 0 && rect.left <= window.innerWidth) {
                visibleElements.push({
                    tag: el.tagName.toLowerCase(),
                    class: el.className,
                    id: el.id,
                    text: el.textContent?.substring(0, 50) || '',
                    position: {
                        top: Math.round(rect.top),
                        left: Math.round(rect.left),
                        width: Math.round(rect.width),
                        height: Math.round(rect.height)
                    },
                    state: captureElementState(el)
                });
            }
        });

        return {
            url: window.location.href,
            timestamp: new Date().toISOString(),
            pageStructure: {
                title: document.title,
                activeElement: document.activeElement?.tagName || 'none',
                focusedElement: captureFocusedElementInfo(),
                visibleElements: visibleElements.slice(0, 20),
                uiStates: captureUIStates(),
                errors: Array.from(document.querySelectorAll('.alert-danger, .error, .text-danger')).map(el => ({
                    text: el.textContent?.substring(0, 100) || '',
                    visible: el.offsetParent !== null
                })).slice(0, 5)
            }
        };
    } catch (error) {
        console.warn('Could not capture visual context:', error);
        return {
            error: 'Visual context capture failed',
            timestamp: new Date().toISOString()
        };
    }
}

function captureElementState(element) {
    const state = {};
    
    // Input/form element states
    if (element.type) state.type = element.type;
    if (element.value !== undefined) state.value = element.value.substring(0, 100);
    if (element.checked !== undefined) state.checked = element.checked;
    if (element.selected !== undefined) state.selected = element.selected;
    if (element.disabled !== undefined) state.disabled = element.disabled;
    
    // ARIA states
    if (element.getAttribute('aria-expanded')) state.ariaExpanded = element.getAttribute('aria-expanded');
    if (element.getAttribute('aria-selected')) state.ariaSelected = element.getAttribute('aria-selected');
    if (element.getAttribute('aria-checked')) state.ariaChecked = element.getAttribute('aria-checked');
    if (element.getAttribute('aria-hidden')) state.ariaHidden = element.getAttribute('aria-hidden');
    
    // Bootstrap/custom states
    if (element.classList.contains('active')) state.active = true;
    if (element.classList.contains('show')) state.show = true;
    if (element.classList.contains('open')) state.open = true;
    if (element.classList.contains('collapsed')) state.collapsed = true;
    
    return Object.keys(state).length > 0 ? state : undefined;
}

function captureFocusedElementInfo() {
    const focused = document.activeElement;
    if (!focused || focused === document.body) return null;
    
    return {
        tag: focused.tagName.toLowerCase(),
        id: focused.id || null,
        class: focused.className || null,
        text: focused.textContent?.substring(0, 30) || null,
        type: focused.type || null
    };
}

function captureUIStates() {
    const states = {};
    
    // Check for open dropdowns
    const openDropdowns = document.querySelectorAll('.dropdown.show, .dropdown-menu.show');
    if (openDropdowns.length > 0) {
        states.openDropdowns = Array.from(openDropdowns).map(dd => ({
            id: dd.id || null,
            class: dd.className,
            text: dd.textContent?.substring(0, 50) || null
        }));
    }
    
    // Check for open modals
    const openModals = document.querySelectorAll('.modal.show, .modal[style*="display: block"]');
    if (openModals.length > 0) {
        states.openModals = Array.from(openModals).map(modal => ({
            id: modal.id || null,
            title: modal.querySelector('.modal-title')?.textContent || null
        }));
    }
    
    // Check for open accordions/collapses
    const openCollapses = document.querySelectorAll('.collapse.show');
    if (openCollapses.length > 0) {
        states.openCollapses = Array.from(openCollapses).map(collapse => ({
            id: collapse.id || null,
            class: collapse.className
        }));
    }
    
    // Check for loading states
    const loadingElements = document.querySelectorAll('.loading, .spinner, [data-loading="true"]');
    if (loadingElements.length > 0) {
        states.loadingStates = Array.from(loadingElements).map(el => ({
            id: el.id || null,
            class: el.className
        }));
    }
    
    // Check for form validation states
    const invalidInputs = document.querySelectorAll('.is-invalid, [aria-invalid="true"]');
    if (invalidInputs.length > 0) {
        states.formValidation = {
            invalidFields: invalidInputs.length,
            fields: Array.from(invalidInputs).map(input => ({
                id: input.id || null,
                name: input.name || null,
                type: input.type || null
            }))
        };
    }
    
    // Check for notifications/alerts
    const notifications = document.querySelectorAll('.alert:not(.d-none), .toast.show, .notification');
    if (notifications.length > 0) {
        states.notifications = Array.from(notifications).map(notif => ({
            type: notif.className.includes('alert-') ? notif.className.match(/alert-(\w+)/)?.[1] : 'unknown',
            text: notif.textContent?.substring(0, 100) || null
        }));
    }
    
    return states;
}

function showBootstrapAlert(title, message, type = 'info') {
    // Remove any existing alerts
    const existingAlert = document.getElementById('bootstrap-alert');
    if (existingAlert) {
        existingAlert.remove();
    }
    
    // Create alert HTML
    const alertHTML = `
        <div id="bootstrap-alert" class="alert alert-${type} alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px; max-width: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
            <div class="d-flex align-items-start">
                <div class="me-3">
                    ${type === 'success' ? '<i class="fas fa-check-circle text-success fs-4"></i>' : 
                      type === 'danger' ? '<i class="fas fa-exclamation-triangle text-danger fs-4"></i>' : 
                      '<i class="fas fa-info-circle text-info fs-4"></i>'}
                </div>
                <div class="flex-grow-1">
                    <h6 class="alert-heading mb-1">${title}</h6>
                    <p class="mb-0 small">${message}</p>
                </div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    // Add to body
    document.body.insertAdjacentHTML('beforeend', alertHTML);
    
    // Start fade after 1 second, dismiss after 2 seconds
    setTimeout(() => {
        const alert = document.getElementById('bootstrap-alert');
        if (alert) {
            alert.style.opacity = '0.5';
        }
    }, 1000);
    
    setTimeout(() => {
        const alert = document.getElementById('bootstrap-alert');
        if (alert) {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }
    }, 2000);
}
</script>

<script>
// Logout function with browser history prevention
function performLogout() {
    if (typeof Swal !== 'undefined') {
        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');
            }
        });
    } else {
        // Fallback if SweetAlert not available
        if (confirm('Are you sure you want to logout?')) {
            window.location.replace('/logout');
        }
    }
}

// Initialize Bootstrap tooltips
document.addEventListener('DOMContentLoaded', function() {
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
});
</script>