<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Local Lendables{% endblock %}</title>
    
    <!-- PWA Meta Tags -->
    <meta name="theme-color" content="#28a745">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="Local Lendables">
    <!-- PWA manifest disabled to prevent navigation conflicts -->
    <!-- <link rel="manifest" href="/manifest.json"> -->
    
    <!-- SEO Meta Tags -->
    <meta name="description" content="{% block description %}Local Lendables - Community lending platform helping small communities share resources through organized lending circles{% endblock %}">
    <meta property="og:title" content="{% block og_title %}Local Lendables{% endblock %}">
    <meta property="og:description" content="{% block og_description %}Community lending platform for sharing resources{% endblock %}">
    <meta property="og:type" content="website">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome CSS - Simplified load -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Local Lendables Custom CSS - MUST load after Bootstrap -->
    <link href="/ll.css?v={{ 'now'|date('U') }}" rel="stylesheet">
    
    <!-- Custom Styles -->
    <style>
        /* Cavolini Font Family */
        @font-face {
            font-family: 'Cavolini';
            src: url('/fonts/CAVOLINI.TTF') format('truetype'),
                 url('/fonts/CAVOLINI.ttf') format('truetype');
            font-weight: normal;
            font-style: normal;
            font-display: swap;
        }
        
        @font-face {
            font-family: 'Cavolini';
            src: url('/fonts/CAVOLINIBOLD.TTF') format('truetype');
            font-weight: bold;
            font-style: normal;
            font-display: swap;
        }
        
        @font-face {
            font-family: 'Cavolini';
            src: url('/fonts/CAVOLINIITALIC.TTF') format('truetype');
            font-weight: normal;
            font-style: italic;
            font-display: swap;
        }
        
        @font-face {
            font-family: 'Cavolini';
            src: url('/fonts/CAVOLINIBOLDITALIC.TTF') format('truetype');
            font-weight: bold;
            font-style: italic;
            font-display: swap;
        }

        :root {
            --primary-color: #28a745;
            --secondary-color: #20c997;
            --light-green: #d4edda;
            --dark-green: #155724;
        }
        
        body {
            font-family: 'Cavolini', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
        }

        /* Typography Rules */
        /* App messaging - Use Cavolini */
        .onlycavolini, .headertitle, 
        h1, h2, h3, h4, h5, h6,
        .alert, .card-header, .navbar-brand,
        .btn, .badge, .toast,
        .form-label, .form-text {
            font-family: 'Cavolini', serif !important;
            font-weight: normal !important;
        }

        /* User input - Use Helvetica/Sans-serif */
        .form-control, .form-select, 
        input[type="text"], input[type="email"], input[type="password"], 
        input[type="number"], input[type="tel"], input[type="url"],
        textarea, select,
        .form-control::placeholder,
        .form-select option {
            font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif !important;
        }
        
        /* Placeholder text styling - lighter grey for better UX */
        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #bbb !important;
            opacity: 1 !important;
        }

        
        .navbar-brand {
            font-weight: bold;
            color: var(--primary-color) !important;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .text-primary {
            color: var(--primary-color) !important;
        }
        
        .bg-primary {
            background-color: var(--primary-color) !important;
        }
        
        .alert-success {
            background-color: var(--light-green);
            border-color: var(--primary-color);
            color: var(--dark-green);
        }
        
        /* Enhanced Bootstrap Tooltip Overrides for Better Visibility */
        .tooltip {
            font-family: 'Cavolini', serif !important;
            font-size: 14px !important;
            font-weight: 600 !important;
        }
        
        .tooltip .tooltip-inner {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
            color: white !important;
            padding: 12px 16px !important;
            border-radius: 8px !important;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3) !important;
            border: 2px solid rgba(255, 255, 255, 0.2) !important;
            max-width: 300px !important;
            text-align: center !important;
            line-height: 1.4 !important;
        }
        
        .tooltip .tooltip-arrow::before {
            border-top-color: #28a745 !important;
        }
        
        .tooltip.bs-tooltip-bottom .tooltip-arrow::before {
            border-bottom-color: #28a745 !important;
        }
        
        .tooltip.bs-tooltip-start .tooltip-arrow::before {
            border-left-color: #28a745 !important;
        }
        
        .tooltip.bs-tooltip-end .tooltip-arrow::before {
            border-right-color: #28a745 !important;
        }
        
        /* Enhanced visibility for tooltip triggers */
        .tooltip-enhanced {
            transition: all 0.2s ease !important;
        }
        
        .tooltip-enhanced:hover {
            transform: scale(1.05) !important;
            filter: brightness(1.1) !important;
        }
        
        /* Tiny breadcrumb styling */
        .breadcrumb.tiny {
            font-size: 0.75rem;
            margin-bottom: 0.25rem;
            padding: 0.25rem 0;
        }
        
        .breadcrumb.tiny .breadcrumb-item + .breadcrumb-item::before {
            font-size: 0.75rem;
        }
        
        /* Mobile-first responsive design */
        @media (max-width: 768px) {
            .container-fluid {
                padding-left: 10px;
                padding-right: 10px;
            }
            
            .demo-user-card {
                min-width: 60px;
            }
            
            .demo-avatar {
                width: 40px !important;
                height: 40px !important;
            }
        }
        
        /* PWA styling for mobile devices */
        @media (display-mode: standalone) {
            body {
                padding-top: env(safe-area-inset-top);
                padding-bottom: env(safe-area-inset-bottom);
            }
        }
        
        /* Force Cavolini font with maximum specificity - Override Bootstrap completely */
        nav.container ol.breadcrumb,
        nav.container ol.breadcrumb li,
        nav.container ol.breadcrumb .breadcrumb-item,
        nav.container ol.breadcrumb .breadcrumb-item a,
        nav.container ol.breadcrumb .breadcrumb-item span,
        .breadcrumb,
        .breadcrumb li,
        .breadcrumb-item,
        .breadcrumb a,
        .breadcrumb span,
        span.giantish,
        .giantish,
        .h5.giantish,
        h5.giantish,
        span.h5.lh-1.giantish,
        span.h5.giantish,
        .row span.h5.lh-1.giantish,
        .col-12 span.h5.lh-1.giantish,
        .text-center span.h5.lh-1.giantish,
        span.giantish.d-flex.align-items-center,
        .col-12 span.giantish,
        .container span.giantish,
        .small:not(.btn),
        small:not(.btn),
        span.small.text-muted,
        .col-12 span.small,
        .container span.small {
            font-family: 'Cavolini', 'Georgia', 'helvetica', 'arial', sans-serif !important;
            font-weight: bold !important;
        }
        
        /* Specific targeting for Messages button to use Cavolini */
        .btn.btn-danger.fw-bold {
            font-family: 'Cavolini', 'Georgia', 'helvetica', 'arial', sans-serif !important;
            font-weight: bold !important;
        }
        
        /* Header navigation should stay as is, remove broad navbar targeting */
        .navbar-brand {
            font-family: 'Cavolini', 'Georgia', 'helvetica', 'arial', sans-serif !important;
        }
    </style>
    
    <!-- Load ll.css last to override Bootstrap styles -->
    <link href="/ll.css?v={{ 'now'|date('U') }}" rel="stylesheet">
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    {% block styles %}{% endblock %}
</head>
<body>
    <!-- Include Common Header -->
    {% include "common-header.html.twig" %}

    <!-- Breadcrumb Navigation -->
    {% if breadcrumbs %}
    <nav class="container mt-2 mb-3">
        <ol class="breadcrumb tiny">
            {% for breadcrumb in breadcrumbs %}
                {% if breadcrumb.url %}
                    <li class="breadcrumb-item">
                        <a href="{{ breadcrumb.url }}" class="text-decoration-none">{{ breadcrumb.label }}</a>
                    </li>
                {% else %}
                    <li class="breadcrumb-item active" aria-current="page">{{ breadcrumb.label }}</li>
                {% endif %}
            {% endfor %}
        </ol>
    </nav>
    {% endif %}

    <!-- Main Content -->
    {% block content %}{% endblock %}

    <!-- Footer -->
    <footer class="bg-light mt-5 py-4">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-primary">Local Lendables</h6>
                    <p class="small text-muted">
                        Building stronger communities through organized sharing and lending circles.
                    </p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="small text-muted">
                        (c) 2025 mwmwm, inc.
                    </p>
                </div>
            </div>
        </div>
    </footer>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Toast Container for Enhanced Notifications -->
    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
        <!-- Toasts will be dynamically inserted here -->
    </div>
    
    <!-- Header Search Functionality -->

    
    <!-- Enhanced Notification System -->
    <script>
        // Enhanced notification system with Bootstrap toasts
        window.LocalLendables = window.LocalLendables || {};
        
        // Create beautiful success toast
        LocalLendables.showSuccessToast = function(title, message, duration = 5000) {
            const toastContainer = document.querySelector('.toast-container');
            const toastId = 'toast-' + Date.now();
            
            const toastHTML = `
                <div id="${toastId}" class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}">
                    <div class="d-flex">
                        <div class="toast-body">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-check-circle me-2"></i>
                                <div>
                                    <strong>${title}</strong><br>
                                    <span class="small">${message}</span>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            `;
            
            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            const toastElement = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            
            // Remove from DOM after hiding
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        };
        
        // Create beautiful error toast
        LocalLendables.showErrorToast = function(title, message, duration = 8000) {
            const toastContainer = document.querySelector('.toast-container');
            const toastId = 'toast-' + Date.now();
            
            const toastHTML = `
                <div id="${toastId}" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}">
                    <div class="d-flex">
                        <div class="toast-body">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <div>
                                    <strong>${title}</strong><br>
                                    <span class="small">${message}</span>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            `;
            
            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            const toastElement = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            
            // Remove from DOM after hiding
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        };
        
        // Create beautiful info toast
        LocalLendables.showInfoToast = function(title, message, duration = 6000) {
            const toastContainer = document.querySelector('.toast-container');
            const toastId = 'toast-' + Date.now();
            
            const toastHTML = `
                <div id="${toastId}" class="toast align-items-center text-bg-info border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}">
                    <div class="d-flex">
                        <div class="toast-body">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-info-circle me-2"></i>
                                <div>
                                    <strong>${title}</strong><br>
                                    <span class="small">${message}</span>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            `;
            
            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            const toastElement = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            
            // Remove from DOM after hiding
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        };
        
        // Enhanced confirmation modal
        LocalLendables.showConfirmModal = function(title, message, confirmText = 'Confirm', onConfirm = null, onCancel = null) {
            const modalId = 'confirm-modal-' + Date.now();
            const modalHTML = `
                <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="fas fa-question-circle me-2 text-warning"></i>${title}
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p class="mb-0">${message}</p>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="${modalId}-cancel">
                                    <i class="fas fa-times me-1"></i>Cancel
                                </button>
                                <button type="button" class="btn btn-primary" id="${modalId}-confirm">
                                    <i class="fas fa-check me-1"></i>${confirmText}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            const modalElement = document.getElementById(modalId);
            const modal = new bootstrap.Modal(modalElement);
            
            // Set up event handlers
            document.getElementById(modalId + '-confirm').addEventListener('click', () => {
                modal.hide();
                if (onConfirm) onConfirm();
            });
            
            document.getElementById(modalId + '-cancel').addEventListener('click', () => {
                modal.hide();
                if (onCancel) onCancel();
            });
            
            // Clean up DOM when hidden
            modalElement.addEventListener('hidden.bs.modal', () => {
                modalElement.remove();
            });
            
            modal.show();
        };
        
        // Unified showToast function for backward compatibility
        LocalLendables.showToast = function(title, message, type = 'info', duration = 5000) {
            try {
                switch(type.toLowerCase()) {
                    case 'success':
                        LocalLendables.showSuccessToast(title, message, duration);
                        break;
                    case 'error':
                    case 'danger':
                        LocalLendables.showErrorToast(title, message, duration);
                        break;
                    case 'info':
                    case 'warning':
                    default:
                        LocalLendables.showInfoToast(title, message, duration);
                        break;
                }
            } catch (error) {
                console.error('Toast error:', error);
                // Fallback to alert if toasts fail
                alert(title + ': ' + message);
            }
        };
    </script>
    
    <!-- Initialize Bootstrap Tooltips -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize all tooltips with enhanced settings
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl, {
                    html: true,
                    trigger: 'hover focus',
                    delay: { show: 200, hide: 100 },
                    placement: 'top',
                    animation: true,
                    customClass: 'enhanced-tooltip'
                });
            });
            
            // Special handling for enhanced tooltips
            var enhancedTooltips = [].slice.call(document.querySelectorAll('.tooltip-enhanced[title]'));
            enhancedTooltips.forEach(function(element) {
                new bootstrap.Tooltip(element, {
                    html: true,
                    trigger: 'hover focus',
                    delay: { show: 150, hide: 50 },
                    placement: 'top',
                    animation: true,
                    customClass: 'enhanced-tooltip-special'
                });
            });
        });
    </script>
    
    <!-- QR Code Generator using API -->
    <script>
    // Simple, reliable QR code generation
    async function generateQRCode(container, size = 256, itemId = null, userId = null) {
        try {
            container.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Generating QR code...</div>';
            
            // Generate a new QR session
            const params = new URLSearchParams();
            if (itemId) params.append('itemId', itemId);
            if (userId) params.append('userId', userId);
            
            const response = await fetch(`/api/generate-qr-session?${params}`);
            
            if (!response.ok) {
                throw new Error(`Session failed: ${response.status}`);
            }
            
            const sessionData = await response.json();
            console.log('Session data:', sessionData);
            
            if (sessionData && sessionData.mobileUrl) {
                container.innerHTML = '';
                
                // Use reliable external QR service
                const img = document.createElement('img');
                img.src = `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(sessionData.mobileUrl)}`;
                img.style.width = `${size}px`;
                img.style.height = `${size}px`;
                img.style.border = '1px solid #ddd';
                img.style.display = 'block';
                img.style.margin = '0 auto';
                img.alt = 'QR Code for Mobile Camera';
                
                img.onload = () => {
                    console.log('QR code loaded successfully');
                };
                
                img.onerror = () => {
                    console.warn('QR image failed, showing manual link');
                    container.innerHTML = `
                        <div class="text-center p-3 border">
                            <i class="fas fa-mobile-alt mb-2" style="font-size: 2rem;"></i><br>
                            <strong>Mobile Camera Access:</strong><br>
                            <a href="${sessionData.mobileUrl}" target="_blank" class="btn btn-primary btn-sm mt-2">
                                Open Camera Interface
                            </a><br>
                            <small class="text-muted mt-2 d-block">
                                Click link or copy URL to mobile device
                            </small>
                        </div>
                    `;
                };
                
                container.appendChild(img);
                
                // Add expiration notice
                const notice = document.createElement('div');
                notice.className = 'text-muted text-center mt-2';
                notice.innerHTML = '<small>QR code expires in 5 minutes</small>';
                container.appendChild(notice);
                
            } else {
                throw new Error('No mobile URL in response');
            }
        } catch (error) {
            console.error('QR generation error:', error);
            container.innerHTML = `
                <div class="text-center text-danger p-3">
                    <i class="fas fa-exclamation-triangle mb-2"></i><br>
                    QR Code Error<br>
                    <small>${error.message}</small><br>
                    <button onclick="generateQRCode(this.closest('.modal-body').querySelector('#qrcode'), 200)" class="btn btn-sm btn-primary mt-2">
                        Try Again
                    </button>
                </div>
            `;
        }
    }

    // Legacy function for backward compatibility
    function generateQRCodeSimple(text, container, size = 256) {
        container.innerHTML = '';
        const img = document.createElement('img');
        img.src = `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(text)}`;
        img.style.maxWidth = '100%';
        img.alt = 'QR Code';
        container.appendChild(img);
    }
    </script>
    
    <!-- PWA Service Worker Registration -->
    <!-- Version Footer -->
    <footer class="mt-5 py-3 text-center text-muted border-top">
        <small>LocalLendables v0.88 - Community Resource Sharing Platform</small>
    </footer>

    <script>
        // Service worker disabled to prevent navigation conflicts in Replit environment
        // if ('serviceWorker' in navigator) {
        //     window.addEventListener('load', function() {
        //         navigator.serviceWorker.register('/sw.js')
        //             .then(function(registration) {
        //                 console.log('SW registered: ', registration);
        //             })
        //             .catch(function(registrationError) {
        //                 console.log('SW registration failed: ', registrationError);
        //             });
        //     });
        // }
    </script>
    
    <!-- Real-time Search Functionality -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Prevent multiple initialization
        if (window.searchInitialized) {
            return;
        }
        window.searchInitialized = true;

        const searchInput = document.getElementById('headerSearchInput');
        const searchResults = document.getElementById('searchResults');
        const searchInputMobile = document.getElementById('headerSearchInputMobile');
        const searchResultsMobile = document.getElementById('searchResultsMobile');
        let searchTimeout;
        let currentRequest = null;

        function setupSearchInput(input, results) {
            if (input && results) {
                input.addEventListener('input', function() {
                    const query = this.value.trim();
                    
                    // Clear previous timeout
                    clearTimeout(searchTimeout);
                    
                    // Hide results if query is too short
                    if (query.length < 3) {
                        results.style.display = 'none';
                        return;
                    }
                    
                    // Debounce search to avoid too many API calls
                    searchTimeout = setTimeout(() => {
                        performSearch(query, results);
                    }, 300);
                });

                // Hide search results when clicking outside
                document.addEventListener('click', function(e) {
                    if (!input.contains(e.target) && !results.contains(e.target)) {
                        results.style.display = 'none';
                    }
                });

                // Show search results when focusing on input (if there's content)
                input.addEventListener('focus', function() {
                    if (this.value.trim().length >= 3 && results.innerHTML.trim()) {
                        results.style.display = 'block';
                    }
                });
            }
        }

        // Setup both desktop and mobile search inputs
        setupSearchInput(searchInput, searchResults);
        setupSearchInput(searchInputMobile, searchResultsMobile);

        async function performSearch(query, resultsContainer) {
            // Cancel previous request if still pending
            if (currentRequest) {
                currentRequest.abort();
            }

            try {
                const controller = new AbortController();
                currentRequest = controller;

                const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
                    signal: controller.signal
                });
                const data = await response.json();
                
                if (currentRequest === controller && data.results) {
                    displaySearchResults(data.results, resultsContainer);
                    currentRequest = null;
                }
            } catch (error) {
                if (error.name !== 'AbortError' && currentRequest) {
                    console.error('Search error:', error);
                    resultsContainer.innerHTML = '<div class="p-3 text-danger">Search error occurred</div>';
                    resultsContainer.style.display = 'block';
                    currentRequest = null;
                }
            }
        }

        function displaySearchResults(results, resultsContainer) {
            const { items, categories, pages } = results;
            let html = '';

            // Items section
            if (items && items.length > 0) {
                html += '<div class="p-2 border-bottom bg-light"><strong class="small text-muted">Matches:</strong></div>';
                items.forEach(item => {
                    const imageHtml = item.image ? 
                        `<img src="/lendable_items/${item.image}" class="me-2 flex-shrink-0" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;" onerror="this.style.display='none'">` : 
                        '<div class="me-2 bg-secondary rounded flex-shrink-0" style="width: 40px; height: 40px;"></div>';
                    
                    const priceHtml = item.price && item.price > 0 ? 
                        `<span class="badge bg-danger ms-2 flex-shrink-0">$${item.price}/day</span>` : 
                        '<span class="badge bg-success ms-2 flex-shrink-0 badge-nowrap">Lendable</span>';
                    
                    html += `
                        <a href="${item.url}" class="dropdown-item d-flex align-items-start py-2 text-decoration-none" style="overflow: hidden; white-space: normal;">
                            ${imageHtml}
                            <div class="flex-grow-1 min-width-0" style="white-space: normal;">
                                <div class="fw-medium" style="word-wrap: break-word; overflow-wrap: break-word;">${escapeHtml(item.title)}</div>
                                <div class="small text-muted" style="word-wrap: break-word; overflow-wrap: break-word;">by ${escapeHtml(item.owner)} • ${escapeHtml(item.category || 'Uncategorized')}</div>
                                ${item.description ? `<div class="small text-muted" style="word-wrap: break-word; overflow-wrap: break-word;">${escapeHtml(item.description.substring(0, 80))}${item.description.length > 80 ? '...' : ''}</div>` : ''}
                            </div>
                            ${priceHtml}
                        </a>`;
                });
            }

            // Categories section
            if (categories && categories.length > 0) {
                html += '<div class="p-2 border-bottom bg-light"><strong class="small text-muted">CATEGORIES</strong></div>';
                categories.forEach(cat => {
                    html += `
                        <a href="${cat.url}" class="dropdown-item d-flex align-items-center py-2 text-decoration-none" style="white-space: normal;">
                            <i class="fas fa-tag me-3 text-primary"></i>
                            <span style="word-wrap: break-word; overflow-wrap: break-word;">${escapeHtml(cat.title)}</span>
                        </a>`;
                });
            }

            // Pages section
            if (pages && pages.length > 0) {
                html += '<div class="p-2 border-bottom bg-light"><strong class="small text-muted">PAGES</strong></div>';
                pages.forEach(page => {
                    html += `
                        <a href="${page.url}" class="dropdown-item d-flex align-items-start py-2 text-decoration-none" style="white-space: normal;">
                            <i class="fas fa-file-alt me-3 text-secondary"></i>
                            <div style="white-space: normal;">
                                <div class="fw-medium" style="word-wrap: break-word; overflow-wrap: break-word;">${escapeHtml(page.title)}</div>
                                <div class="small text-muted" style="word-wrap: break-word; overflow-wrap: break-word;">${escapeHtml(page.description)}</div>
                            </div>
                        </a>`;
                });
            }

            if (!html) {
                html = '<div class="p-3 text-muted text-center">No results found</div>';
            }

            resultsContainer.innerHTML = html;
            resultsContainer.style.display = 'block';
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    });
    </script>

    {% block scripts %}{% endblock %}
    
    <!-- CSS Debug Overlay - Only shows when ?css-debug is in URL -->
    <div id="cssDebugOverlay" style="display: none;">
        <div class="container-fluid mt-3">
            <div class="row">
                <!-- CSS Classes Sidebar -->
                <div class="col-3 bg-light border-end" style="height: 100vh; overflow-y: auto; position: fixed; left: 0; top: 0; z-index: 9999; box-shadow: 2px 0 5px rgba(0,0,0,0.1);">
                    <div class="p-2" style="padding-top: 20px;">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="fw-bold text-primary mb-0">CSS Debug</h6>
                            <button class="btn btn-sm btn-outline-danger" onclick="closeCSSDebug()" style="font-size: 10px;">×</button>
                        </div>
                        <div id="cssClassesList" style="font-size: 10pt;">
                            <!-- Classes will be populated by JavaScript -->
                        </div>
                    </div>
                </div>
                
                <!-- CSS Editor Panel -->
                <div id="cssEditor" class="col-6 bg-white border" style="position: fixed; right: 0; top: 0; height: 100vh; overflow-y: auto; z-index: 9998; display: none; box-shadow: -2px 0 5px rgba(0,0,0,0.1);">
                    <div class="p-3">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 id="editingClassName" class="text-primary mb-0"></h6>
                            <button class="btn btn-sm btn-outline-secondary" onclick="closeCSSEditor()" style="font-size: 10px;">×</button>
                        </div>
                        <form id="cssEditForm">
                            <div class="row g-2">
                                <div class="col-6">
                                    <label class="form-label small">Font Size</label>
                                    <input type="text" class="form-control form-control-sm" name="fontSize" placeholder="e.g., 14px, 1rem">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Font Family</label>
                                    <select class="form-select form-select-sm" name="fontFamily">
                                        <option value="">Default (Serif)</option>
                                        <option value="'Cavolini', 'Georgia', serif">'Cavolini'</option>
                                        <option value="'Helvetica Neue', Helvetica, Arial, sans-serif">Helvetica</option>
                                        <option value="-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif">Sans-Serif</option>
                                        <option value="'Times New Roman', Times, serif">Serif</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Font Weight</label>
                                    <select class="form-select form-select-sm" name="fontWeight">
                                        <option value="">Default</option>
                                        <option value="100">100</option>
                                        <option value="200">200</option>
                                        <option value="300">300</option>
                                        <option value="400">400</option>
                                        <option value="500">500</option>
                                        <option value="600">600</option>
                                        <option value="700">700</option>
                                        <option value="800">800</option>
                                        <option value="900">900</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Line Height</label>
                                    <input type="text" class="form-control form-control-sm" name="lineHeight" placeholder="e.g., 1.5, 24px">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Color</label>
                                    <input type="text" class="form-control form-control-sm" name="color" placeholder="e.g., #333, red">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Margin T</label>
                                    <input type="text" class="form-control form-control-sm" name="marginTop" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Margin R</label>
                                    <input type="text" class="form-control form-control-sm" name="marginRight" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Margin B</label>
                                    <input type="text" class="form-control form-control-sm" name="marginBottom" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Margin L</label>
                                    <input type="text" class="form-control form-control-sm" name="marginLeft" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Padding T</label>
                                    <input type="text" class="form-control form-control-sm" name="paddingTop" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Padding R</label>
                                    <input type="text" class="form-control form-control-sm" name="paddingRight" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Padding B</label>
                                    <input type="text" class="form-control form-control-sm" name="paddingBottom" placeholder="10px">
                                </div>
                                <div class="col-3">
                                    <label class="form-label small">Padding L</label>
                                    <input type="text" class="form-control form-control-sm" name="paddingLeft" placeholder="10px">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Background Color</label>
                                    <input type="text" class="form-control form-control-sm" name="backgroundColor" placeholder="e.g., #f8f9fa, blue">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Border</label>
                                    <input type="text" class="form-control form-control-sm" name="border" placeholder="e.g., 1px solid #ccc">
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary btn-sm me-1">Apply</button>
                                <button type="button" class="btn btn-secondary btn-sm me-1" onclick="resetClass()">Reset</button>
                                <button type="button" class="btn btn-warning btn-sm" onclick="exportCSS()">Export</button>
                            </div>
                        </form>
                        
                        <!-- Export Area -->
                        <div id="exportArea" class="mt-3" style="display: none;">
                            <h6 class="small">Generated CSS</h6>
                            <textarea id="exportedCSS" class="form-control form-control-sm" rows="8" readonly></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    let currentClassName = '';
    let cssChanges = {};

    document.addEventListener('DOMContentLoaded', function() {
        // Check if css-debug parameter is in URL
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('css-debug')) {
            document.getElementById('cssDebugOverlay').style.display = 'block';
            extractCSSClasses();
            setupFormHandler();
        }
    });

    function extractCSSClasses() {
        // Define classes from ll.css and custom.css files - TEXT AND IMAGE DISPLAY ONLY
        const predefinedClasses = [
            // Text display classes
            'giantish',        // Font styling for large text
            'giant',           // Font styling for very large text  
            'giantette',       // Font styling for medium-small text
            'giantelle',       // Font styling for medium-small text (Cavolini)
            'midhead',         // Header text styling
            'middrop',         // Dropdown text styling
            'midsmall',        // Small text styling
            'midi',            // USED FOR: Item Descriptions (medium text)
            'medium',          // USED FOR: Button text (ALPHABETIC, CATEGORIES, etc.)
            'mini',            // Very small text styling
            'headermini',      // Header mini text styling
            'h1',              // Heading 1 font family
            'h2',              // Heading 2 font family
            'h3',              // Heading 3 font family
            'h4',              // Heading 4 font family - USED FOR: Page Titles (Our Lendable Items Listings)
            'h5',              // Heading 5 font family
            'h6',              // Heading 6 font family - USED FOR: Item Titles, Quick Stats headers
            'onlycavolini',    // Force Cavolini font family
            'small',           // Small text with Cavolini Bold - USED FOR: Category labels, Descriptions, Page descriptions
            'smallplus',       // Slightly larger small text with Cavolini Bold
            'homemidi',        // Home page medium text
            'homehead',        // Home page header text
            'homesmaller',     // Home page smaller text
            'smallerdata',     // Small data text
            'zero',            // Zero padding/line-height for tight spacing
            
            // Bootstrap classes used for content styling
            'fs-md',           // USED FOR: Item Titles (medium font size)
            'fw-medium',       // USED FOR: Item Titles (medium font weight)
            'fw-bold',         // USED FOR: Description labels, price text
            'text-muted',      // USED FOR: Category text, Descriptions, Page descriptions
            'text-primary',    // USED FOR: Category values, owner names
            'text-success'     // USED FOR: Item Title links
        ];
        
        // Filter to only show classes that exist on the page AND are in our predefined list
        const allElements = document.querySelectorAll('*');
        const pageClassSet = new Set();
        
        allElements.forEach(element => {
            if (element.className && typeof element.className === 'string') {
                element.className.split(' ').forEach(className => {
                    if (className.trim()) {
                        pageClassSet.add(className.trim());
                    }
                });
            }
        });
        
        // Only show classes that are both predefined AND actually used on the page
        const relevantClasses = predefinedClasses.filter(className => pageClassSet.has(className));
        const sortedClasses = relevantClasses.sort();
        
        const classListContainer = document.getElementById('cssClassesList');
        
        if (sortedClasses.length === 0) {
            classListContainer.innerHTML = `
                <div class="text-muted" style="font-size: 10pt;">
                    No ll.css/custom.css classes found on this page.
                    <br><br>
                    Available classes: ${predefinedClasses.join(', ')}
                </div>
            `;
            return;
        }
        
        classListContainer.innerHTML = sortedClasses.map(className => `
            <div class="mb-1">
                <button class="btn btn-link p-1 text-start w-100" 
                        style="font-size: 10pt; text-decoration: none;" 
                        onclick="selectClass('${className}')">
                    .${className}
                </button>
            </div>
        `).join('');
    }

    function selectClass(className) {
        currentClassName = className;
        document.getElementById('editingClassName').textContent = `.${className}`;
        document.getElementById('cssEditor').style.display = 'block';
        
        // Get current computed styles for the class
        const elements = document.querySelectorAll(`.${className}`);
        if (elements.length > 0) {
            const computedStyle = window.getComputedStyle(elements[0]);
            populateForm(computedStyle);
        }
        
        // Highlight elements with this class
        highlightElements(className);
    }

    function populateForm(computedStyle) {
        const form = document.getElementById('cssEditForm');
        
        // Populate form fields with current values
        form.fontSize.value = computedStyle.fontSize || '';
        
        // Handle font family mapping
        const fontFamily = computedStyle.fontFamily || '';
        if (fontFamily.includes('Cavolini')) {
            form.fontFamily.value = "'Cavolini', 'Georgia', serif";
        } else if (fontFamily.includes('Helvetica') || fontFamily.includes('Arial')) {
            form.fontFamily.value = "'Helvetica Neue', Helvetica, Arial, sans-serif";
        } else if (fontFamily.includes('system') || fontFamily.includes('Segoe UI')) {
            form.fontFamily.value = "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";
        } else if (fontFamily.includes('Times') || fontFamily.includes('serif')) {
            form.fontFamily.value = "'Times New Roman', Times, serif";
        } else {
            form.fontFamily.value = '';
        }
        
        form.fontWeight.value = computedStyle.fontWeight || '';
        form.lineHeight.value = computedStyle.lineHeight || '';
        form.color.value = computedStyle.color || '';
        form.marginTop.value = computedStyle.marginTop || '';
        form.marginRight.value = computedStyle.marginRight || '';
        form.marginBottom.value = computedStyle.marginBottom || '';
        form.marginLeft.value = computedStyle.marginLeft || '';
        form.paddingTop.value = computedStyle.paddingTop || '';
        form.paddingRight.value = computedStyle.paddingRight || '';
        form.paddingBottom.value = computedStyle.paddingBottom || '';
        form.paddingLeft.value = computedStyle.paddingLeft || '';
        form.backgroundColor.value = computedStyle.backgroundColor || '';
        form.border.value = computedStyle.border || '';
    }

    function highlightElements(className) {
        // Remove previous highlights
        document.querySelectorAll('.css-debug-highlight').forEach(el => {
            el.classList.remove('css-debug-highlight');
        });
        
        // Add highlight to current class elements
        document.querySelectorAll(`.${className}`).forEach(el => {
            el.classList.add('css-debug-highlight');
        });
    }

    function setupFormHandler() {
        document.getElementById('cssEditForm').addEventListener('submit', function(e) {
            e.preventDefault();
            applyChanges();
        });
    }

    function applyChanges() {
        if (!currentClassName) return;
        
        const form = document.getElementById('cssEditForm');
        const formData = new FormData(form);
        
        // Build CSS rule
        let cssRule = `.${currentClassName} {`;
        
        for (let [key, value] of formData.entries()) {
            if (value.trim()) {
                // Convert camelCase to kebab-case
                const cssProperty = key.replace(/([A-Z])/g, '-$1').toLowerCase();
                
                // Handle font-family specially - add fallback if not specified
                if (key === 'fontFamily') {
                    if (value === '') {
                        // Default to serif if not specified
                        cssRule += `\n  font-family: serif;`;
                    } else {
                        cssRule += `\n  font-family: ${value};`;
                    }
                } else {
                    cssRule += `\n  ${cssProperty}: ${value};`;
                }
            }
        }
        
        cssRule += '\n}';
        
        // Store the change
        cssChanges[currentClassName] = cssRule;
        
        // Apply the change immediately
        updateStyleSheet();
    }

    function updateStyleSheet() {
        // Remove existing debug stylesheet
        const existingStyle = document.getElementById('css-debug-styles');
        if (existingStyle) {
            existingStyle.remove();
        }
        
        // Create new stylesheet with all changes
        const style = document.createElement('style');
        style.id = 'css-debug-styles';
        
        let allCSS = '/* CSS Debug Changes */\n';
        allCSS += '.css-debug-highlight { outline: 2px solid #ff6b6b !important; outline-offset: 2px; }\n\n';
        
        Object.values(cssChanges).forEach(rule => {
            allCSS += rule + '\n\n';
        });
        
        style.textContent = allCSS;
        document.head.appendChild(style);
    }

    function resetClass() {
        if (!currentClassName) return;
        
        delete cssChanges[currentClassName];
        updateStyleSheet();
        
        // Clear form
        document.getElementById('cssEditForm').reset();
        
        // Remove highlights
        document.querySelectorAll('.css-debug-highlight').forEach(el => {
            el.classList.remove('css-debug-highlight');
        });
    }

    function exportCSS() {
        let exportedCSS = '/* Exported CSS Changes */\n\n';
        
        Object.values(cssChanges).forEach(rule => {
            exportedCSS += rule + '\n\n';
        });
        
        document.getElementById('exportedCSS').value = exportedCSS;
        document.getElementById('exportArea').style.display = 'block';
    }

    function closeCSSDebug() {
        document.getElementById('cssDebugOverlay').style.display = 'none';
        // Remove the css-debug parameter from URL
        const url = new URL(window.location);
        url.searchParams.delete('css-debug');
        window.history.replaceState({}, '', url);
    }

    function closeCSSEditor() {
        document.getElementById('cssEditor').style.display = 'none';
        // Remove highlights
        document.querySelectorAll('.css-debug-highlight').forEach(el => {
            el.classList.remove('css-debug-highlight');
        });
    }

    // Initialize highlight styles
    const highlightStyle = document.createElement('style');
    highlightStyle.textContent = `
    .css-debug-highlight {
        outline: 2px solid #ff6b6b !important;
        outline-offset: 2px;
    }
    `;
    document.head.appendChild(highlightStyle);
    </script>
</body>
</html>