{% extends "layout.html.twig" %}
{# Cache buster: {{ "now"|date("U") }} #}

{% block title %}Edit My Item - LocalLendables{% endblock %}

{% block content %}


<div class="container-fluid px-3 py-4">
  <!-- Header Section -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-start mb-3">
        <div class="d-flex align-items-start">
          <img src="/lendables/logo_edit_600.png" alt="Edit" class="me-3" style="height: 100px;">
          <div>
            <h1 class="h3 mb-2 text-primary fw-bold onlycavolini headertitle">Edit My Item</h1>
            <p class="text-muted mb-0">Update your item details</p>
          </div>
        </div>

      </div>
    </div>
  </div>

  <!-- Edit Mode Notice -->
  <div class="row mb-3">
    <div class="col-12">
      <div class="alert alert-warning d-flex justify-content-between align-items-center py-2">
        <div class="d-flex align-items-center">
          <i class="fas fa-edit me-2"></i>
          <div>
            <h6 class="mb-0 small">Edit Mode</h6>
            <small class="text-muted">You are editing this item. Changes will be saved when you submit.</small>
          </div>
        </div>
        <div class="d-flex gap-2">
          <a href="/print-labels/{{ item.id }}" class="btn btn-sm" style="background: white; color: #198754; border: 2px solid #198754;">
            <i class="fas fa-print me-2"></i>Print 5160 Labels
          </a>
          <a href="/item/{{ item.id }}" class="btn btn-sm" style="background: white; color: #0d6efd; border: 2px solid #0d6efd;">
            <i class="fas fa-eye me-2"></i>View as if Borrower
          </a>
        </div>
      </div>
    </div>
  </div>

  <div class="row justify-content-center">
    <div class="col-12 col-xl-10">
      <div class="card border-0 shadow-sm no-hover">
        <div class="card-body p-4">
          <form id="editItemForm" action="/api/items/{{ item.id }}" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="_method" value="PUT">
            
            <div class="row">
              <!-- Left Column - Main Form (2/3 width) -->
              <div class="col-md-8">
                <!-- Item Title -->
                <div class="mb-4">
                  <label for="title" class="form-label fw-semibold">Item Title <span class="text-danger">*</span></label>
                  <input type="text" class="form-control" id="title" name="title" 
                         value="{{ item.name }}" required>
                </div>

                <!-- Category -->
                <div class="mb-4">
                  <label for="category" class="form-label fw-semibold">Category <span class="text-danger">*</span></label>
                  <select class="form-select" id="category" name="category" required>
                    <option value="">Choose a category</option>
                    {% for category in categories %}
                    <option value="{{ category.id }}" {% if item.category == category.id %}selected{% endif %}>{{ category.category }}</option>
                    {% endfor %}
                  </select>
                </div>

                <!-- Description -->
                <div class="mb-4">
                  <label for="description" class="form-label fw-semibold">Description <span class="text-danger">*</span></label>
                  <textarea class="form-control" id="description" name="description" rows="4" required
                            placeholder="Describe your item, its condition, and any special notes...">{{ item.description }}</textarea>
                  <div class="form-text">Details help others find and understand your Lendable.</div>
                </div>

                <!-- Special Instructions -->
                <div class="mb-4">
                  <label for="specialInstructions" class="form-label fw-semibold">Special Instructions</label>
                  <textarea class="form-control" id="specialInstructions" name="specialInstructions" rows="3"
                            placeholder="Any special care instructions, pickup notes, or usage guidelines...">{% if item.specialInstructions and item.specialInstructions != 'false' %}{{ item.specialInstructions }}{% endif %}</textarea>
                  <div class="form-text">Add notes about care, pickup, or special requirements</div>
                </div>

                <!-- Condition -->
                <div class="mb-4">
                  <label for="condition" class="form-label fw-semibold">Condition <span class="text-danger">*</span></label>
                  <select class="form-select" id="condition" name="condition" required>
                    <option value="">Select condition</option>
                    <option value="excellent" {% if item.condition == 'excellent' %}selected{% endif %}>Excellent - Like new</option>
                    <option value="good" {% if item.condition == 'good' %}selected{% endif %}>Good - Minor wear</option>
                    <option value="fair" {% if item.condition == 'fair' %}selected{% endif %}>Fair - Some wear but functional</option>
                    <option value="poor" {% if item.condition == 'poor' %}selected{% endif %}>Poor - Significant wear</option>
                  </select>
                </div>
              </div>

              <!-- Right Column - Photos & Settings (1/3 width) -->
              <div class="col-md-4">
                <!-- Current Images with Make Primary Options -->
                {% set validImages = [] %}
                {% if item.primaryLogo and item.primaryLogo != 'default-placeholder.jpg' %}
                  {% set validImages = validImages|merge([{filename: item.primaryLogo, isPrimary: true}]) %}
                {% endif %}
                {% if item.extraImages %}
                  {% set extraImageList = item.extraImages|split(',') %}
                  {% for image in extraImageList %}
                    {% if image|trim and image|trim != 'default-placeholder.jpg' %}
                      {% set validImages = validImages|merge([{filename: image|trim, isPrimary: false}]) %}
                    {% endif %}
                  {% endfor %}
                {% endif %}
                
                {% if validImages|length > 0 %}
                <div class="mb-3">
                  <h6>Current Images:</h6>
                  <div class="row g-2" id="currentImagesContainer">
                    {% for imageData in validImages|slice(0, 3) %}
                    <div class="col-4">
                      <div class="position-relative">
                        <img src="/lendable_items/{{ imageData.filename }}" 
                             class="img-fluid rounded border" 
                             alt="{{ imageData.isPrimary ? 'Primary' : 'Extra' }}"
                             style="width: 100%; height: 120px; object-fit: cover;"
                             onerror="this.parentElement.parentElement.style.display='none';">
                        {% if imageData.isPrimary %}
                          <span class="badge bg-success position-absolute top-0 start-0 m-1">Primary</span>
                        {% else %}
                          <button type="button" class="btn btn-sm btn-outline-primary position-absolute bottom-0 start-0 m-1" 
                                  onclick="makePrimary('{{ imageData.filename }}')">
                            <i class="fas fa-star me-1"></i>Make Primary
                          </button>
                        {% endif %}
                        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" 
                                onclick="removeCurrentImage('{{ imageData.filename }}')">×</button>
                      </div>
                    </div>
                    {% endfor %}
                  </div>
                  {% if validImages|length > 3 %}
                    <small class="text-muted">Showing first 3 images. Additional images available.</small>
                  {% endif %}
                </div>
                {% endif %}

                <!-- Item Photos -->
                <div class="mb-4">
                  <label class="form-label fw-semibold">Item Photo(s)</label>
                  
                  <!-- Image Capture Options -->
                  <div class="d-grid gap-3 mb-3">
                    <!-- Paste Image Section - Smart Global Paste (FIRST) -->
                    <div>
                      <div class="btn btn-outline-success btn-sm w-100 d-flex align-items-center justify-content-center" id="pasteIndicator" style="background-color: white; color: #198754; border-style: dashed;">
                        <i class="fas fa-clipboard me-2"></i><span id="pasteStatusText">Paste Image Anywhere</span>
                      </div>
                      
                      <!-- Paste preview (appears after image is pasted) -->
                      <div id="pastePreview" class="mt-2" style="display: none;">
                        <small class="text-muted d-block mb-1">Pasted Image:</small>
                        <div class="border rounded p-2 bg-light position-relative">
                          <img id="pastePreviewImg" class="img-fluid rounded" style="max-width: 100%; max-height: 100px; object-fit: cover;" alt="Pasted image">
                          <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" onclick="removePastedImage()">×</button>
                        </div>
                      </div>
                    </div>
                    
                    <!-- Camera Section (SECOND) -->
                    <div>
                      <button type="button" class="btn btn-outline-success btn-sm p-1 w-100" onclick="takePhoto()">
                        <img src="/lendables/logo_photo_laptop_600.png" alt="Camera" style="width: 100px; height: auto;" class="me-2 desktop-camera-icon">
                        <img src="/lendables/logo_photo_phone_600.png" alt="Camera" style="width: 100px; height: auto;" class="me-2 mobile-camera-icon">
                        Take Photo
                      </button>
                      <!-- Camera preview would appear here if implemented -->
                    </div>

                    <!-- Mobile QR Section (THIRD) - hidden on mobile -->
                    <div class="desktop-only-qr">
                      <button type="button" class="btn btn-outline-success btn-sm mobile-qr-btn p-1 w-100" onclick="showQRCode()">
                        <img src="/lendables/logo_photo_phone_600.png" alt="Mobile" style="width: 100px; height: auto;" class="me-2">Use Phone+QR
                      </button>
                      <!-- Mobile QR uploads preview would appear here -->
                      <div id="mobileQRPreviewContainer" class="mt-2" style="display: none;">
                        <small class="text-muted d-block mb-1">Mobile QR Photos:</small>
                        <div id="mobileQRPreviewGrid" class="d-flex flex-wrap gap-2"></div>
                      </div>
                    </div>
                    
                    <!-- Upload File Section (FOURTH) -->
                    <div>
                      <button type="button" class="btn btn-outline-primary btn-sm w-100" onclick="document.getElementById('imageUpload').click()">
                        <i class="fas fa-upload me-2"></i>Upload File
                      </button>
                      <!-- Upload File Preview (appears directly below Upload File button) -->
                      <div id="uploadPreviewContainer" class="mt-2" style="display: none;">
                        <small class="text-muted d-block mb-1">Uploaded Files:</small>
                        <div id="uploadPreviewGrid" class="d-flex flex-wrap gap-2"></div>
                      </div>
                    </div>
                  </div>

                  <!-- Hidden file inputs -->
                  <input type="file" class="d-none" id="imageUpload" name="newImages" 
                         accept="image/*" multiple onchange="handleImageUpload(this)">
                  
                  <!-- All Images Summary (appears after any images are added) -->
                  <div id="imagePreviewContainer" class="mb-3" style="display: none;">
                    <h6 class="small">All New Images to Add:</h6>
                    <div id="imagePreviewGrid" class="d-flex flex-wrap gap-2"></div>
                  </div>
                  
                  <div class="alert alert-info small">
                    <i class="fas fa-info-circle me-2"></i>
                    Add images, then confirm which is the "primary" image. Changes take effect on "submit."
                  </div>
                </div>

                <!-- Lending Terms Section -->
                <div class="mb-4">
                  <h6 class="fw-semibold mb-3 onlycavolini">Lending Terms</h6>
                  
                  <!-- Default: Free Lending -->
                  <div id="freeLendingAlert" class="alert alert-success d-flex align-items-center mb-3 p-2 {% if item.pricePerDay and item.pricePerDay > 0 %}faded{% endif %}">
                    <i class="fas fa-hand-holding-heart me-2"></i>
                    <span class="small"><strong>Lendable</strong> - Free community sharing (default)</span>
                  </div>
                  
                  <!-- Checkbox to enable rental options -->
                  <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" id="enableRental" 
                           {% if item.pricePerDay and item.pricePerDay > 0 %}checked{% endif %}
                           onchange="toggleRentalOptions()">
                    <label class="form-check-label small" for="enableRental">
                      <strong>Enable rental options</strong> - Charge daily rate for this item
                    </label>
                  </div>
                  
                  <!-- Rental Options -->
                  <div id="rentalOptions" {% if not item.pricePerDay or item.pricePerDay == 0 %}style="display: none;"{% endif %}>
                    <div class="mb-3">
                      <label for="dailyRate" class="form-label small">Daily Rate <span class="text-danger">*</span></label>
                      <div class="input-group input-group-sm">
                        <span class="input-group-text">$</span>
                        <input type="number" class="form-control" id="dailyRate" name="dailyRate" 
                               min="0.01" step="0.01" value="{{ item.pricePerDay ? item.pricePerDay : '' }}" placeholder="5.00">
                      </div>
                      <div class="form-text">Amount per day for rental</div>
                    </div>
                    
                    <div class="mb-3">
                      <label for="deposit" class="form-label small">Security Deposit (Optional)</label>
                      <div class="input-group input-group-sm">
                        <span class="input-group-text">$</span>
                        <input type="number" class="form-control" id="deposit" name="deposit" 
                               min="0" step="0.01" value="{{ item.deposit ? item.deposit : '' }}" placeholder="25.00">
                      </div>
                      <div class="form-text">Refundable upon return</div>
                    </div>
                  </div>
                </div>

                <!-- Availability -->
                <div class="mb-4">
                  <label for="availability" class="form-label fw-semibold">Availability</label>
                  <select class="form-select form-select-sm" id="availability" name="availability">
                    <option value="available" {% if item.availability == 'available' %}selected{% endif %}>Available</option>
                    <option value="unavailable" {% if item.availability == 'unavailable' %}selected{% endif %}>Not available right now</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- Form Actions -->
            <div class="row">
              <div class="col-12">
                <div class="d-flex gap-3 pt-3">
                  <button type="submit" class="btn btn-success flex-fill">
                    <i class="fas fa-save me-2"></i>Save Changes
                  </button>
                  <button type="button" class="btn btn-outline-info" onclick="viewCalendar()">
                    <img src="/lendables/logo_item_calendar_600.png" alt="Calendar" style="width: 16px; height: 16px; margin-right: 5px;">View Calendar
                  </button>
                  <button type="button" class="btn btn-outline-secondary" onclick="cancelEdit()">
                    <i class="fas fa-times me-2"></i>Cancel
                  </button>
                  <button type="button" class="btn btn-outline-danger" onclick="deleteItem()">
                    <i class="fas fa-trash me-2"></i>Delete Item
                  </button>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Calendar Modal -->
<div class="modal fade" id="calendarModal" tabindex="-1" aria-labelledby="calendarModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="calendarTitle">Lendable Calendar - {{ item.title }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="editCalendarContent">
          <!-- Calendar content will be loaded here -->
          <div class="text-center">
            <div class="spinner-border" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading loan calendar...</p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<style>
        .image-card .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(220, 53, 69, 0.9);
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            font-size: 12px;
            cursor: pointer;
        }
        
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }
        
        .image-card {
            position: relative;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .image-card img {
            width: 100%;
            height: 80px;
            object-fit: cover;
        }
        
        .paste-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            background-color: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
            display: none;
        }
        
        .paste-area.active {
            display: block;
            border-color: #28a745;
            background-color: #e8f5e8;
        }
        
        .paste-area:hover {
            border-color: #28a745;
            background-color: #e8f5e8;
        }
        
        .polling-indicator {
            display: none;
            text-align: center;
            padding: 15px;
            background-color: #e3f2fd;
            border-radius: 8px;
            margin: 10px 0;
        }
        
        .polling-indicator.active {
            display: block;
        }
        
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #2196F3;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Faded state for free lending alert when rental options are enabled */
        .faded {
            opacity: 0.3 !important;
            transition: opacity 0.3s ease;
        }

        /* Custom Mobile QR Button Styling */
        .mobile-qr-btn.btn-outline-success {
            border-color: #1e5631 !important;
            color: #1e5631 !important;
            background-color: transparent !important;
        }
        
        .mobile-qr-btn.btn-outline-success:hover {
            border-color: #1e5631 !important;
            color: white !important;
            background-color: #1e5631 !important;
        }
        
        .mobile-qr-btn.btn-outline-success:focus {
            border-color: #1e5631 !important;
            color: #1e5631 !important;
            box-shadow: 0 0 0 0.2rem rgba(30, 86, 49, 0.25) !important;
        }
        
        /* White background for Print and View buttons */
        .alert-warning .btn {
            background-color: white !important;
        }
        
        .alert-warning {
            background-color: white !important;
            border-color: #ffc107 !important;
        }
</style>

<!-- QR Code Modal -->
<div id="qrModal" class="modal fade" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Mobile Camera Access</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center">
        <div id="qrcode" class="mb-3"></div>
        <p class="text-muted">Scan this QR code with your phone to open the camera interface</p>
        <div class="alert alert-info">
          <i class="fas fa-info-circle me-2"></i>
          This will open a mobile-optimized camera page on your phone
        </div>
        <div id="pollingIndicator" class="polling-indicator">
          <div class="spinner"></div>
          Waiting for photos from mobile device...
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="successModalLabel">
          <i class="fas fa-check-circle me-2"></i>Success!
        </h5>
      </div>
      <div class="modal-body text-center">
        <div class="mb-3">
          <i class="fas fa-check-circle text-success" style="font-size: 3rem;"></i>
        </div>
        <p id="successMessage" class="mb-3"></p>
        <div class="progress mb-3" style="height: 6px;">
          <div class="progress-bar bg-success" role="progressbar" style="width: 0%"></div>
        </div>
        <small class="text-muted">Redirecting to item details...</small>
      </div>
    </div>
  </div>
</div>

<!-- Status Messages -->
<div id="statusMessage" class="status-message" style="display: none;"></div>

<script>
// QR Code Generation v4.0 - Complete Rewrite {{ "now"|date("U") }}
console.log('NEW QR SCRIPT v4.0 loaded at:', new Date().toISOString());
let pollingInterval;
let qrCodeGenerated = false;

// Brand new QR function with different name to bypass cache
window.newQRFunction = async function() {
    console.log('🟢 NEW QR FUNCTION v4.0 CALLED');
    
    try {
        // Find the modal and container
        const modal = document.querySelector('#qrModal');
        const container = modal ? modal.querySelector('#qrcode') : document.getElementById('qrcode');
        
        if (!container) {
            console.error('❌ No QR container found');
            LocalLendables.showToast('Error', 'QR container not found', 'error');
            return;
        }
        
        console.log('✅ Container found:', container.id);
        
        // Show loading
        container.innerHTML = `
            <div class="text-center p-4">
                <div class="spinner-border text-primary mb-3"></div>
                <h5>Creating QR Code...</h5>
            </div>
        `;
        
        // Get session
        console.log('📡 Fetching QR session...');
        const response = await fetch('/api/generate-qr-session');
        console.log('📡 Response:', response.status);
        
        if (!response.ok) {
            throw new Error('Session request failed: ' + response.status);
        }
        
        const sessionData = await response.json();
        console.log('📦 Session data:', sessionData);
        
        if (!sessionData.mobileUrl) {
            throw new Error('No mobile URL received');
        }
        
        // Create QR code HTML (reduced to 2/3 size for better message visibility)
        const qrImageUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=167x167&data=' + encodeURIComponent(sessionData.mobileUrl);
        console.log('🖼️ QR image URL:', qrImageUrl);
        
        container.innerHTML = `
            <div class="card border-success">
                <div class="card-header bg-success text-white text-center">
                    <h5 class="mb-0"><i class="fas fa-qrcode"></i> QR Code Ready</h5>
                </div>
                <div class="card-body text-center">
                    <img src="${qrImageUrl}" 
                         alt="QR Code for Mobile Access" 
                         class="img-fluid border rounded shadow-sm"
                         style="max-width: 250px;"
                         onload="console.log('✅ QR image loaded successfully')"
                         onerror="console.log('❌ QR image failed'); this.parentNode.innerHTML='<div class=\\'alert alert-warning\\'>QR service unavailable<br><a href=\\'${sessionData.mobileUrl}\\' target=\\'_blank\\' class=\\'btn btn-primary\\'>Direct Link</a></div>'">
                    <div class="mt-3">
                        <small class="text-muted">
                            <i class="fas fa-camera"></i> Scan with phone camera<br>
                            <i class="fas fa-clock"></i> Expires in 5 minutes
                        </small>
                    </div>
                </div>
            </div>
        `;
        
        console.log('✅ QR code created successfully!');
        qrCodeGenerated = true;
        
    } catch (error) {
        console.error('❌ QR generation failed:', error);
        const container = document.querySelector('#qrcode');
        if (container) {
            container.innerHTML = `
                <div class="alert alert-danger text-center">
                    <h6><i class="fas fa-exclamation-triangle"></i> QR Generation Failed</h6>
                    <p>${error.message}</p>
                    <button onclick="window.newQRFunction()" class="btn btn-outline-danger btn-sm">
                        <i class="fas fa-redo"></i> Try Again
                    </button>
                </div>
            `;
        }
    }
};

function showMobileQR() {
    console.log('🔄 showMobileQR starting...');
    const qrModal = document.getElementById('qrModal');
    if (!qrModal) {
        console.error('QR modal not found');
        return;
    }
    
    // Show modal first
    const modal = new bootstrap.Modal(qrModal);
    modal.show();
    
    // Wait a moment for modal to render, then generate QR
    setTimeout(() => {
        console.log('🔄 Calling QR function after modal show...');
        window.newQRFunction();
    }, 100);
    
    startPolling();
}

window.generateQRCode = async function() {
    console.log('=== QR GENERATION v3.0 STARTED ===');
    
    // Get the container - try multiple methods
    let qrContainer = document.getElementById('qrcode');
    if (!qrContainer) {
        console.error('QR container #qrcode not found, searching...');
        qrContainer = document.querySelector('#qrcode');
    }
    if (!qrContainer) {
        console.error('Still no QR container found, checking modal...');
        const modal = document.querySelector('#qrModal');
        if (modal) {
            qrContainer = modal.querySelector('[id*="qr"]');
            console.log('Found container in modal:', qrContainer);
        }
    }
    
    if (!qrContainer) {
        console.error('FATAL: No QR container found anywhere!');
        LocalLendables.showToast('Error', 'QR container not found. Please refresh the page.', 'error');
        return;
    }
    
    console.log('QR container found:', qrContainer.id || qrContainer.className);
    
    try {
        // Show loading state
        qrContainer.innerHTML = '<div class="text-center p-3"><div class="spinner-border"></div><br><strong>Loading QR...</strong></div>';
        
        console.log('Making session request...');
        const response = await fetch('/api/generate-qr-session');
        console.log('Response received:', response.status, response.statusText);
        
        if (!response.ok) {
            throw new Error(`Session failed: ${response.status} ${response.statusText}`);
        }
        
        const data = await response.json();
        console.log('Session data:', JSON.stringify(data, null, 2));
        
        if (!data || !data.mobileUrl) {
            throw new Error('Invalid session data - no mobile URL');
        }
        
        // Create the QR code immediately
        const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(data.mobileUrl)}`;
        console.log('QR URL:', qrUrl);
        
        qrContainer.innerHTML = `
            <div class="card">
                <div class="card-body text-center">
                    <h5 class="card-title text-success">
                        <i class="fas fa-qrcode"></i> QR Code Ready
                    </h5>
                    <img src="${qrUrl}" 
                         alt="QR Code" 
                         class="img-fluid mb-3"
                         style="max-width: 200px; border: 1px solid #ddd; border-radius: 8px;"
                         onload="console.log('✓ QR image loaded'); qrCodeGenerated = true;"
                         onerror="console.log('✗ QR image failed'); this.style.display='none'; this.nextElementSibling.style.display='block';">
                    <div style="display: none;" class="alert alert-warning">
                        <strong>Direct Access:</strong><br>
                        <a href="${data.mobileUrl}" target="_blank" class="btn btn-primary">
                            Open Mobile Camera
                        </a>
                    </div>
                    <p class="text-muted small">
                        Scan with phone camera • Expires in 5 minutes
                    </p>
                </div>
            </div>
        `;
        
        console.log('✓ QR code HTML created successfully');
        
    } catch (error) {
        console.error('✗ QR generation failed:', error);
        qrContainer.innerHTML = `
            <div class="alert alert-danger text-center">
                <h6><i class="fas fa-exclamation-triangle"></i> QR Failed</h6>
                <p class="mb-2">${error.message}</p>
                <button onclick="generateQRCode()" class="btn btn-sm btn-outline-danger">
                    <i class="fas fa-redo"></i> Retry
                </button>
            </div>
        `;
    }
};

// Mobile upload polling with intelligent stop
let processedImageCount = 0;
let lastImageCount = 0;

function startPolling() {
    const pollingIndicator = document.getElementById('pollingIndicator');
    if (pollingIndicator) {
        pollingIndicator.classList.add('active');
    }
    processedImageCount = 0;
    lastImageCount = 0;
    pollingInterval = setInterval(checkMobileUpload, 2000);
}

function stopPolling() {
    if (pollingInterval) {
        clearInterval(pollingInterval);
        pollingInterval = null;
    }
    const pollingIndicator = document.getElementById('pollingIndicator');
    if (pollingIndicator) {
        pollingIndicator.classList.remove('active');
    }
}

async function checkMobileUpload() {
    try {
        const response = await fetch('/api/mobile-upload-status');
        const data = await response.json();
        
        if (data.hasUpload) {
            const imageResponse = await fetch('/api/mobile-upload-image');
            
            if (imageResponse.headers.get('content-type')?.includes('application/json')) {
                // Multi-image response from sequential uploads
                const imageData = await imageResponse.json();
                
                // Only process if we have new images
                if (imageData.filenames && imageData.filenames.length > lastImageCount) {
                    console.log(`Processing ${imageData.filenames.length} sequential uploads (${imageData.filenames.length - lastImageCount} new)`);
                    
                    // Process only the new images
                    for (let i = lastImageCount; i < imageData.filenames.length; i++) {
                        const filename = imageData.filenames[i];
                        console.log(`Adding new image: ${filename}`);
                        
                        const imageUrl = `/lendable_items/${filename}`;
                        fetch(imageUrl)
                            .then(response => response.blob())
                            .then(blob => {
                                const file = new File([blob], filename, { type: 'image/jpeg' });
                                addImageToPreview(file, 'mobile');
                            })
                            .catch(err => console.error('Failed to load image:', err));
                    }
                    
                    lastImageCount = imageData.filenames.length;
                    
                    // Stop polling after a few seconds of no new images
                    clearTimeout(this.sequentialTimeout);
                    this.sequentialTimeout = setTimeout(() => {
                        stopPolling();
                        const qrModal = bootstrap.Modal.getInstance(document.getElementById('qrModal'));
                        if (qrModal) qrModal.hide();
                        console.log('No new images for 10 seconds - stopped polling');
                        
                        // Clear uploads to free up storage
                        fetch('/api/mobile-upload-clear', { method: 'POST' });
                    }, 10000);
                }
            } else {
                // Single image blob response (legacy)
                const blob = await imageResponse.blob();
                const file = new File([blob], 'mobile-capture.jpg', { type: 'image/jpeg' });
                addImageToPreview(file);
                
                stopPolling();
                const qrModal = bootstrap.Modal.getInstance(document.getElementById('qrModal'));
                if (qrModal) qrModal.hide();
                
                // Clear uploads
                fetch('/api/mobile-upload-clear', { method: 'POST' });
            }
        }
    } catch (error) {
        console.error('Polling error:', error);
    }
}

// Status messages
function showStatus(message, type) {
    const statusDiv = document.getElementById('statusMessage');
    if (statusDiv) {
        statusDiv.textContent = message;
        statusDiv.className = `status-message status-${type}`;
        statusDiv.style.display = 'block';
        
        setTimeout(() => {
            statusDiv.style.display = 'none';
        }, 5000);
    } else {
        console.warn('Status message element not found:', message);
    }
}

function showSuccessModal(message) {
    const modal = new bootstrap.Modal(document.getElementById('successModal'));
    document.getElementById('successMessage').textContent = message;
    
    // Show modal
    modal.show();
    
    // Animate progress bar
    const progressBar = document.querySelector('#successModal .progress-bar');
    let width = 0;
    const interval = setInterval(() => {
        width += 5;
        progressBar.style.width = width + '%';
        if (width >= 100) {
            clearInterval(interval);
        }
    }, 100);
}

function makePrimary(filename) {
    if (confirm('Make this image the primary image for this item?')) {
        // Add hidden input to mark which image should become primary
        const form = document.getElementById('editItemForm');
        let input = document.querySelector('input[name="newPrimaryImage"]');
        if (!input) {
            input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'newPrimaryImage';
            form.appendChild(input);
        }
        input.value = filename;
        
        // Visual feedback
        showStatus('Primary image will be updated when you save changes', 'info');
        
        // Update visual indicators
        document.querySelectorAll('.badge.bg-success').forEach(badge => {
            if (badge.textContent === 'Primary') {
                badge.remove();
            }
        });
        
        document.querySelectorAll('img[src*="' + filename + '"]').forEach(img => {
            const container = img.parentElement;
            if (!container.querySelector('.badge.bg-success')) {
                const badge = document.createElement('span');
                badge.className = 'badge bg-warning position-absolute top-0 start-0 m-1';
                badge.textContent = 'New Primary';
                container.appendChild(badge);
            }
        });
    }
}

// Image handling functions
let newImageFiles = []; // Store new files for form submission

function updateImageSummary() {
    // This function is called to update the image summary display
    console.log('Updating image summary, total files:', newImageFiles.length);
}

function addImageToPreview(file, source = 'upload') {
    // Add file to our array for form submission
    const fileIndex = newImageFiles.length;
    newImageFiles.push(file);
    console.log('Added image to upload queue:', file.name, 'Total files:', newImageFiles.length);
    
    // Create image preview card
    const imageCard = createImagePreviewCard(file, fileIndex);
    
    // Add to appropriate contextual preview section only
    if (source === 'upload') {
        addToUploadPreview(imageCard);
    } else if (source === 'paste') {
        // Paste images show in paste preview area (existing behavior)
        showPastePreview(file);
    } else if (source === 'camera') {
        // Camera images can go to main summary grid since there's no contextual area for them
        const summaryGrid = document.getElementById('imagePreviewGrid');
        if (summaryGrid) {
            summaryGrid.appendChild(imageCard.cloneNode(true));
            document.getElementById('imagePreviewContainer').style.display = 'block';
        }
    }
    
    // Update radio buttons for primary image selection only if there are multiple new images
    if (newImageFiles.length > 1) {
        updatePrimaryImageRadios();
    }
}

function createImagePreviewCard(file, fileIndex) {
    const imageCard = document.createElement('div');
    imageCard.className = 'position-relative';
    imageCard.style.width = '100px';
    imageCard.setAttribute('data-file-index', fileIndex);
    
    const img = document.createElement('img');
    img.src = URL.createObjectURL(file);
    img.alt = 'New image';
    img.className = 'img-fluid rounded border';
    img.style.width = '100%';
    img.style.height = '80px';
    img.style.objectFit = 'cover';
    
    // Primary radio button (only show if multiple images or will have multiple)
    const showPrimaryRadio = newImageFiles.length > 1 || fileIndex > 0;
    if (showPrimaryRadio) {
        const radioDiv = document.createElement('div');
        radioDiv.className = 'position-absolute bottom-0 start-0 m-1';
        radioDiv.innerHTML = `
            <div class="form-check bg-white rounded px-1" style="font-size: 0.7rem;">
                <input class="form-check-input" type="radio" name="newPrimaryImageIndex" 
                       id="newPrimary${fileIndex}" value="${fileIndex}" ${fileIndex === 0 ? 'checked' : ''}>
                <label class="form-check-label" for="newPrimary${fileIndex}">Primary</label>
            </div>
        `;
        imageCard.appendChild(radioDiv);
    }
    
    // Remove button
    const removeBtn = document.createElement('button');
    removeBtn.type = 'button';
    removeBtn.className = 'btn btn-sm btn-danger position-absolute top-0 end-0 m-1';
    removeBtn.textContent = '×';
    removeBtn.style.fontSize = '0.7rem';
    removeBtn.onclick = () => {
        removeNewImage(fileIndex);
    };
    
    imageCard.appendChild(img);
    imageCard.appendChild(removeBtn);
    
    return imageCard;
}

function addToUploadPreview(imageCard) {
    const uploadContainer = document.getElementById('uploadPreviewContainer');
    const uploadGrid = document.getElementById('uploadPreviewGrid');
    
    if (uploadContainer && uploadGrid) {
        uploadGrid.appendChild(imageCard);
        uploadContainer.style.display = 'block';
    }
}

function showPastePreview(file) {
    const pastePreview = document.getElementById('pastePreview');
    const pastePreviewImg = document.getElementById('pastePreviewImg');
    
    if (pastePreview && pastePreviewImg) {
        const reader = new FileReader();
        reader.onload = function(e) {
            pastePreviewImg.src = e.target.result;
            pastePreview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    }
}

function removePastedImage() {
    console.log('removePastedImage called');
    
    // Hide paste preview
    const pastePreview = document.getElementById('pastePreview');
    if (pastePreview) {
        pastePreview.style.display = 'none';
    }
    
    // Remove the pasted image from newImageFiles if it exists
    const pasteIndex = newImageFiles.findIndex(file => file.name.startsWith('pasted-image-'));
    if (pasteIndex !== -1) {
        newImageFiles.splice(pasteIndex, 1);
        console.log('Removed pasted image from upload queue');
    }
    
    // Reset paste indicator to ready state
    const indicator = document.getElementById('pasteIndicator');
    const statusText = document.getElementById('pasteStatusText');
    if (indicator && statusText) {
        indicator.style.borderColor = '#198754';
        indicator.style.backgroundColor = 'white';
        indicator.style.color = '#198754';
        statusText.textContent = 'Paste Image Anywhere';
    }
    
    // Refresh the preview grid
    rebuildImagePreviews();
    
    showStatus('Pasted image removed', 'info');
}

function removeNewImage(fileIndex) {
    // Remove from array (shift indices)
    newImageFiles.splice(fileIndex, 1);
    
    // Remove visual element
    const imageCard = document.querySelector(`[data-file-index="${fileIndex}"]`);
    if (imageCard) {
        imageCard.remove();
    }
    
    // Rebuild entire preview to fix radio buttons and indices
    rebuildImagePreviews();
    
    console.log('Removed image from upload queue, remaining files:', newImageFiles.length);
    
    if (newImageFiles.length === 0) {
        document.getElementById('imagePreviewContainer').style.display = 'none';
    }
}

function updatePrimaryImageRadios() {
    // Update radio buttons for primary image selection in contextual areas
    const uploadGrid = document.getElementById('uploadPreviewGrid');
    const pasteGrid = document.getElementById('pastePreviewGrid');
    
    // Update upload preview radio buttons
    if (uploadGrid) {
        const uploadCards = uploadGrid.querySelectorAll('[data-file-index]');
        uploadCards.forEach((card, index) => {
            const radio = card.querySelector('input[name="primaryImageIndex"]');
            if (radio) {
                radio.value = card.getAttribute('data-file-index');
            }
        });
    }
    
    // Update paste preview radio buttons
    if (pasteGrid) {
        const pasteCards = pasteGrid.querySelectorAll('[data-file-index]');
        pasteCards.forEach((card, index) => {
            const radio = card.querySelector('input[name="primaryImageIndex"]');
            if (radio) {
                radio.value = card.getAttribute('data-file-index');
            }
        });
    }
}

function rebuildImagePreviews() {
    const container = document.getElementById('imagePreviewContainer');
    const grid = document.getElementById('imagePreviewGrid');
    
    if (!grid || newImageFiles.length === 0) {
        if (container) container.style.display = 'none';
        return;
    }
    
    // Clear existing previews
    grid.innerHTML = '';
    
    // Rebuild all previews with correct indices and radio buttons
    newImageFiles.forEach((file, index) => {
        const imageCard = document.createElement('div');
        imageCard.className = 'position-relative';
        imageCard.style.width = '120px';
        imageCard.setAttribute('data-file-index', index);
        
        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);
        img.alt = 'New image';
        img.className = 'img-fluid rounded border';
        img.style.width = '100%';
        img.style.height = '100px';
        img.style.objectFit = 'cover';
        
        // Primary radio button (show if multiple images)
        if (newImageFiles.length > 1) {
            const radioDiv = document.createElement('div');
            radioDiv.className = 'position-absolute bottom-0 start-0 m-1';
            radioDiv.innerHTML = `
                <div class="form-check bg-white rounded px-2 py-1" style="font-size: 0.75rem;">
                    <input class="form-check-input" type="radio" name="newPrimaryImageIndex" 
                           id="newPrimary${index}" value="${index}" ${index === 0 ? 'checked' : ''}>
                    <label class="form-check-label" for="newPrimary${index}">Primary</label>
                </div>
            `;
            imageCard.appendChild(radioDiv);
        }
        
        // Remove button
        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'btn btn-sm btn-danger position-absolute top-0 end-0 m-1';
        removeBtn.textContent = '×';
        removeBtn.onclick = () => removeNewImage(index);
        
        imageCard.appendChild(img);
        imageCard.appendChild(removeBtn);
        grid.appendChild(imageCard);
    });
    
    container.style.display = 'block';
}

function handleImageUpload(input) {
    const files = Array.from(input.files);
    console.log('Processing', files.length, 'uploaded files');
    files.forEach(file => addImageToPreview(file, 'upload'));
    
    // Clear the file input to prevent duplication in FormData
    input.value = '';
    console.log('Cleared file input to prevent duplication');
}

// Smart Global Paste System - Always Active
function initializeSmartPaste() {
    console.log('Initializing smart global paste system');
    
    // Function to handle successful paste
    function handleSuccessfulPaste(file) {
        console.log('Image found in clipboard');
        
        // Check if we already have 3 images
        if (newImageFiles.length >= 3) {
            showStatus('Maximum 3 images allowed. Please remove an existing image first.', 'warning');
            return;
        }
        
        // Create unique filename with timestamp and random component
        const timestamp = Date.now();
        const randomId = Math.floor(Math.random() * 10000);
        const uniqueFile = new File([file], `pasted-image-${timestamp}-${randomId}.png`, { type: file.type });
        
        // Show paste preview
        const pastePreview = document.getElementById('pastePreview');
        const pastePreviewImg = document.getElementById('pastePreviewImg');
        
        const reader = new FileReader();
        reader.onload = function(e) {
            pastePreviewImg.src = e.target.result;
            pastePreview.style.display = 'block';
        };
        reader.readAsDataURL(uniqueFile);
        
        // Add to upload queue
        addImageToPreview(uniqueFile, 'paste');
        
        // Update paste indicator
        updatePasteIndicator('success');
        
        showStatus(`Image pasted successfully! (${newImageFiles.length}/3 images)`, 'success');
        
        // Reset indicator after brief success feedback
        setTimeout(() => {
            updatePasteIndicator('ready');
        }, 2000);
    }
    
    // Update paste indicator visual state
    function updatePasteIndicator(state) {
        const indicator = document.getElementById('pasteIndicator');
        const statusText = document.getElementById('pasteStatusText');
        
        switch(state) {
            case 'ready':
                indicator.style.borderColor = '#198754';
                indicator.style.backgroundColor = 'white';
                indicator.style.color = '#198754';
                statusText.textContent = 'Paste Image Anywhere';
                break;
            case 'detecting':
                indicator.style.borderColor = '#0dcaf0';
                indicator.style.backgroundColor = '#e7f3ff';
                indicator.style.color = '#0dcaf0';
                statusText.textContent = 'Image detected in clipboard...';
                break;
            case 'success':
                indicator.style.borderColor = '#28a745';
                indicator.style.backgroundColor = '#d4edda';
                indicator.style.color = '#28a745';
                statusText.textContent = 'Image pasted successfully!';
                break;
            case 'error':
                indicator.style.borderColor = '#dc3545';
                indicator.style.backgroundColor = '#f8d7da';
                indicator.style.color = '#dc3545';
                statusText.textContent = 'No image found in clipboard';
                break;
        }
    }
    
    // Global paste handler - always active
    document.addEventListener('paste', function(e) {
        // Only handle paste if target is not a text input/textarea
        const target = e.target;
        const isTextInput = target.tagName === 'INPUT' && (target.type === 'text' || target.type === 'email' || target.type === 'search');
        const isTextArea = target.tagName === 'TEXTAREA';
        const isContentEditable = target.contentEditable === 'true';
        
        if (isTextInput || isTextArea || isContentEditable) {
            // Let normal text pasting happen
            return;
        }
        
        console.log('Global paste handler triggered');
        updatePasteIndicator('detecting');
        
        const items = e.clipboardData.items;
        let imageFound = false;
        
        for (let item of items) {
            if (item.type.indexOf('image') !== -1) {
                e.preventDefault(); // Only prevent default if we find an image
                const file = item.getAsFile();
                handleSuccessfulPaste(file);
                imageFound = true;
                break;
            }
        }
        
        if (!imageFound) {
            // Reset indicator if no image found
            setTimeout(() => {
                updatePasteIndicator('error');
                setTimeout(() => {
                    updatePasteIndicator('ready');
                }, 1500);
            }, 500);
        }
    });
    
    // Add visual feedback for keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
            // Visual feedback that paste shortcut was detected
            updatePasteIndicator('detecting');
        }
    });
    
    console.log('Smart paste system initialized - paste anywhere on the page!');
}

function takePhoto() {
    // Use getUserMedia to access device camera directly
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // Create camera modal
        const cameraModal = document.createElement('div');
        cameraModal.className = 'modal fade';
        cameraModal.id = 'cameraModal';
        cameraModal.innerHTML = `
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Take Photo</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body text-center">
                        <video id="cameraVideo" width="100%" height="300" autoplay playsinline></video>
                        <canvas id="cameraCanvas" style="display: none;"></canvas>
                        <div class="mt-3">
                            <button type="button" class="btn btn-success" id="captureBtn">
                                <i class="fas fa-camera me-2"></i>Capture Photo
                            </button>
                            <button type="button" class="btn btn-secondary ms-2" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(cameraModal);
        
        const modal = new bootstrap.Modal(cameraModal);
        const video = cameraModal.querySelector('#cameraVideo');
        const canvas = cameraModal.querySelector('#cameraCanvas');
        const captureBtn = cameraModal.querySelector('#captureBtn');
        let stream = null;
        
        // Start camera
        navigator.mediaDevices.getUserMedia({ 
            video: { 
                facingMode: 'environment', // Try to use back camera on mobile
                width: { ideal: 1280 },
                height: { ideal: 720 }
            } 
        })
        .then(function(mediaStream) {
            stream = mediaStream;
            video.srcObject = stream;
            modal.show();
        })
        .catch(function(err) {
            console.error('Camera access denied:', err);
            // Fallback to file input if camera access fails
            fallbackToFileInput();
            return;
        });
        
        // Capture photo
        captureBtn.addEventListener('click', function() {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0);
            
            canvas.toBlob(function(blob) {
                const file = new File([blob], 'camera-capture.jpg', { type: 'image/jpeg' });
                addImageToPreview(file, 'camera');
                showStatus('Photo captured successfully!', 'success');
                
                // Stop camera and close modal
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
                modal.hide();
                cameraModal.remove();
            }, 'image/jpeg', 0.85);
        });
        
        // Clean up when modal is closed
        cameraModal.addEventListener('hidden.bs.modal', function() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            cameraModal.remove();
        });
        
    } else {
        // Fallback for browsers without camera support
        fallbackToFileInput();
    }
}

function fallbackToFileInput() {
    // Create a hidden file input for photo capture
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.capture = 'environment';
    input.style.display = 'none';
    
    input.onchange = function(event) {
        const file = event.target.files[0];
        if (file) {
            addImageToPreview(file, 'camera');
            showStatus('Photo selected successfully!', 'success');
        }
        // Clean up
        document.body.removeChild(input);
    };
    
    document.body.appendChild(input);
    input.click();
    showStatus('Camera not available, using file picker instead', 'info');
}

function startCamera() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                showStatus('Camera feature coming soon', 'info');
                stream.getTracks().forEach(track => track.stop());
            })
            .catch(err => {
                showStatus('Camera access denied or not available', 'error');
            });
    } else {
        showStatus('Camera not supported on this device', 'error');
    }
}

// Form functions
function toggleRentalOptions() {
    const checkbox = document.getElementById('enableRental');
    const options = document.getElementById('rentalOptions');
    const freeLendingAlert = document.getElementById('freeLendingAlert');
    
    if (checkbox.checked) {
        options.style.display = 'block';
        freeLendingAlert.classList.add('faded');
    } else {
        options.style.display = 'none';
        freeLendingAlert.classList.remove('faded');
    }
}

function removeCurrentImage(imageName) {
    console.log('Remove image:', imageName);
    
    if (confirm('Are you sure you want to remove this image?')) {
        // Add to removal queue
        let removedImages = [];
        const existingInput = document.querySelector('input[name="removedImages"]');
        if (existingInput) {
            removedImages = JSON.parse(existingInput.value || '[]');
        }
        
        if (!removedImages.includes(imageName)) {
            removedImages.push(imageName);
        }
        
        // Update or create hidden input
        const form = document.getElementById('editItemForm');
        let input = document.querySelector('input[name="removedImages"]');
        if (!input) {
            input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'removedImages';
            form.appendChild(input);
        }
        input.value = JSON.stringify(removedImages);
        
        // Hide the image visually
        const imageContainer = document.querySelector(`img[src*="${imageName}"]`)?.closest('.col-4');
        if (imageContainer) {
            imageContainer.style.opacity = '0.3';
            imageContainer.style.pointerEvents = 'none';
            
            // Add removal indicator
            const badge = document.createElement('span');
            badge.className = 'badge bg-danger position-absolute top-50 start-50 translate-middle';
            badge.textContent = 'Will be removed';
            badge.style.zIndex = '1000';
            imageContainer.style.position = 'relative';
            imageContainer.appendChild(badge);
        }
        
        showStatus('Image will be removed when you save changes', 'info');
    }
}

function togglePreviewMode() {
    console.log('Toggle preview mode');
    // Implementation for preview mode
}

function cancelEdit() {
    if (confirm('Are you sure you want to cancel? Unsaved changes will be lost.')) {
        window.history.back();
    }
}

async function deleteItem() {
    if (confirm('Are you sure you want to delete this item? This action cannot be undone.')) {
        try {
            const response = await fetch(`/api/items/{{ item.id }}`, {
                method: 'DELETE'
            });
            
            if (response.ok) {
                // Show success message and redirect to browse
                LocalLendables.showToast('Success', 'Item deleted successfully!', 'success');
                setTimeout(() => window.location.href = '/browse', 1500);
            } else {
                const errorData = await response.json();
                const errorMessage = errorData.error || 'Unknown error';
                
                // Show more user-friendly error messages
                if (errorMessage.includes('active loans')) {
                    LocalLendables.showToast('Cannot Delete', 'Cannot delete this item because someone is currently borrowing it. Please wait for the item to be returned before deleting.', 'error');
                } else {
                    LocalLendables.showToast('Error', 'Failed to delete item: ' + errorMessage, 'error');
                }
            }
        } catch (error) {
            console.error('Delete error:', error);
            LocalLendables.showToast('Error', 'Failed to delete item', 'error');
        }
    }
}

function viewCalendar() {
    // Open calendar modal similar to item detail page
    const calendarModal = new bootstrap.Modal(document.getElementById('calendarModal'));
    calendarModal.show();
    loadCalendarData();
}

function loadCalendarData() {
    const itemId = {{ item.id }};
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1; // JavaScript months are 0-indexed
    
    // Update calendar title
    document.getElementById('calendarTitle').textContent = `Lendable Calendar - {{ item.title }}`;
    
    fetch(`/api/items/${itemId}/calendar/${year}/${month}`)
        .then(response => response.json())
        .then(data => {
            renderEditCalendarData(data.loans || []);
        })
        .catch(error => {
            console.error('Error loading calendar:', error);
            const content = document.getElementById('editCalendarContent');
            if (content) {
                content.innerHTML = '<div class="alert alert-danger">Failed to load calendar data.</div>';
            }
        });
}

function renderEditCalendarData(loans) {
    const content = document.getElementById('editCalendarContent');
    
    if (!content) {
        console.error('editCalendarContent element not found');
        return;
    }
    
    if (loans.length === 0) {
        content.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-calendar-alt fa-3x mb-3"></i>
                <h5>No Upcoming Reservations</h5>
                <div class="calendar-container mt-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <button class="btn btn-sm btn-outline-secondary" onclick="changeEditMonth(-1)">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <h6 id="editCalendarMonth" class="mb-0"></h6>
                        <button class="btn btn-sm btn-outline-secondary" onclick="changeEditMonth(1)">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th class="text-center">S</th>
                                <th class="text-center">M</th>
                                <th class="text-center">T</th>
                                <th class="text-center">W</th>
                                <th class="text-center">T</th>
                                <th class="text-center">F</th>
                                <th class="text-center">S</th>
                            </tr>
                        </thead>
                        <tbody id="editCalendarGrid">
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        // Initialize calendar for owner view
        initializeEditCalendar();
        return;
    }
    
    let html = '<div class="timeline">';
    
    loans.forEach(loan => {
        const borrowedDate = new Date(loan.borrowedDate).toLocaleDateString();
        const expectedReturnDate = new Date(loan.expectedReturnDate).toLocaleDateString();
        const actualReturnDate = loan.actualReturnDate ? new Date(loan.actualReturnDate).toLocaleDateString() : null;
        
        let statusBadge = '';
        let statusClass = '';
        
        if (loan.status === 'completed') {
            statusBadge = '<span class="badge bg-success">Completed</span>';
            statusClass = 'border-success';
        } else if (loan.status === 'active') {
            statusBadge = '<span class="badge bg-primary">Active</span>';
            statusClass = 'border-primary';
        } else if (loan.status === 'overdue') {
            statusBadge = '<span class="badge bg-danger">Overdue</span>';
            statusClass = 'border-danger';
        } else if (loan.status === 'reserved') {
            statusBadge = '<span class="badge bg-warning">Reserved</span>';
            statusClass = 'border-warning';
        }
        
        html += `
            <div class="timeline-item border ${statusClass} mb-3 p-3 rounded">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="mb-1">${loan.borrowerName} ${statusBadge}</h6>
                        <div class="text-muted">
                            <small>Borrowed:</small> <strong>${borrowedDate}</strong><br>
                            <small>Expected Return:</small> <strong>${expectedReturnDate}</strong>
                        </div>
                        ${actualReturnDate ? `
                            <div class="mt-2">
                                <small class="text-muted">Actual Return Date:</small>
                                <div><strong>${actualReturnDate}</strong></div>
                            </div>
                        ` : ''}
                        ${loan.price ? `
                            <div class="mt-2">
                                <small class="text-muted">Price:</small>
                                <div><strong>$${loan.price}</strong></div>
                            </div>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    content.innerHTML = html;
}

// Edit calendar variables
let editCurrentDate = new Date();

// Initialize edit calendar
function initializeEditCalendar() {
    renderEditCalendarView();
}

// Change month in edit calendar
function changeEditMonth(direction) {
    editCurrentDate.setMonth(editCurrentDate.getMonth() + direction);
    renderEditCalendarView();
}

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

function updateCalendarDisplay(data, year, month) {
    const { availability, loans } = data;
    
    if (loans && loans.length > 0) {
        let loansHTML = '<div class="mb-3"><h6>Current Reservations:</h6><ul class="list-unstyled">';
        loans.forEach(loan => {
            const startDate = new Date(loan.borrowedDate).toLocaleDateString();
            const endDate = new Date(loan.expectedReturnDate).toLocaleDateString();
            loansHTML += `<li><strong>${loan.borrowerName}</strong>: ${startDate} - ${endDate} (${loan.status})</li>`;
        });
        loansHTML += '</ul></div>';
        
        document.getElementById('calendarContainer').innerHTML = loansHTML + 
            '<div class="text-center text-muted">Calendar integration shows available dates and existing bookings here.</div>';
    } else {
        document.getElementById('calendarContainer').innerHTML = 
            '<div class="text-center text-muted">No reservations currently scheduled.</div>' +
            '<div class="text-center text-muted mt-2">Calendar integration would show available dates and existing bookings here.</div>';
    }
}

// Form submission - wait for DOM to be ready
let isSubmitting = false; // Prevent multiple submissions

document.addEventListener('DOMContentLoaded', function() {
    // Initialize smart paste system
    initializeSmartPaste();
    
    const editForm = document.getElementById('editItemForm');
    if (editForm) {
        editForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Prevent multiple simultaneous submissions
            if (isSubmitting) {
                console.log('Form already submitting, ignoring duplicate submission');
                return;
            }
            
            isSubmitting = true;
            console.log('Starting form submission...');
            
            // Disable submit button to provide visual feedback
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton?.textContent;
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.textContent = 'Saving...';
            }
            
            const formData = new FormData(this);
            
            // Add new images from paste/upload to formData
            console.log('Preparing form submission with', newImageFiles.length, 'new images');
            newImageFiles.forEach((file, index) => {
                formData.append('newImages', file);
                console.log('Added image to form:', file.name, 'Size:', file.size);
            });
            
            // Add primary image selection for new images
            const selectedPrimary = document.querySelector('input[name="newPrimaryImageIndex"]:checked');
            if (selectedPrimary && newImageFiles.length > 1) {
                formData.append('newImagePrimaryIndex', selectedPrimary.value);
                console.log('Selected primary image index:', selectedPrimary.value);
            }
            
            try {
                const response = await fetch(this.action, {
                    method: 'PUT',
                    body: formData
                });
                
                if (response.ok) {
                    const updateMessage = newImageFiles.length > 0 
                        ? `Item updated successfully! ${newImageFiles.length} image(s) added with Image Canon standards.`
                        : 'Item updated successfully!';
                    showSuccessModal(updateMessage);
                    setTimeout(() => {
                        window.location.href = '/item/{{ item.id }}';
                    }, 2000);
                } else {
                    showStatus('Failed to update item', 'error');
                }
            } catch (error) {
                console.error('Update error:', error);
                showStatus('Failed to update item', 'error');
            } finally {
                // Re-enable form submission
                isSubmitting = false;
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.textContent = originalText || 'Save Changes';
                }
            }
        });
    } else {
        console.warn('Edit form not found');
    }
    
    // Initialize calendar modal event listener
    const calendarModal = document.getElementById('calendarModal');
    if (calendarModal) {
        calendarModal.addEventListener('show.bs.modal', function () {
            loadCalendarData();
        });
    }
    const enableRentalCheckbox = document.getElementById('enableRental');
    if (enableRentalCheckbox) {
        enableRentalCheckbox.addEventListener('change', toggleRentalOptions);
    }
});
</script>

{% endblock %}/* Cache buster: 1750350891 */
