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

{% block title %}Create New 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_create_600.png" alt="Create New" class="me-3" style="height: 100px;">
          <div>
            <h1 class="h3 mb-2 text-primary fw-bold onlycavolini headertitle">Create a New Lendable Item</h1>
            <p class="text-muted mb-0">Add an item to share with your community</p>
          </div>
        </div>

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

  <div class="row justify-content-center">
    <div class="col-12 col-xl-10">
      <div class="card border-0 shadow-sm">
        <div class="card-body p-4">
          <form id="createItemForm" enctype="multipart/form-data">
            <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" required
                         placeholder="What are you sharing?">

                </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 }}">{{ 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..."></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..."></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">Excellent - Like new</option>
                    <option value="good">Good - Minor wear</option>
                    <option value="fair">Fair - Some wear but functional</option>
                    <option value="poor">Poor - Significant wear</option>
                  </select>
                </div>
              </div>

              <!-- Right Column - Photos & Settings (1/3 width) -->
              <div class="col-md-4">
                <!-- Item Photos -->
                <div class="mb-4">
                  <label class="form-label fw-semibold">Item Photo(s)</label>
                  
                  <!-- Image Preview Container -->
                  <div id="imagePreviewContainer" class="mt-2 mb-3" style="display: none;">
                    <h6 class="small mb-2 text-success">Images to Add:</h6>
                    <div id="imagePreviewGrid" class="d-flex flex-wrap gap-2 mb-2">
                      <!-- Images will be added here dynamically -->
                    </div>
                  </div>
                  
                  <!-- Image Capture Options -->
                  <div class="d-grid gap-2 mb-3">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="triggerFileUpload()">
                      <i class="fas fa-upload me-2"></i>Upload File
                    </button>
                    <button type="button" class="btn btn-outline-success btn-sm" id="pasteButton" onclick="enablePasteMode()" style="background-color: white; color: #198754;">
                      <i class="fas fa-clipboard me-2"></i><span id="pasteButtonText">Click to Paste Image</span>
                    </button>
                    
                    <!-- Paste area (appears after Paste Image button) -->
                    <div id="pasteArea" class="border border-dashed rounded p-1 text-center" 
                         style="display: none; cursor: pointer;" tabindex="0">
                      <i class="fas fa-clipboard text-info me-2"></i>
                      <span class="text-muted small">Click here and paste an image (Ctrl+V / Cmd+V)</span>
                    </div>
                    
                    <button type="button" class="btn btn-outline-success btn-sm p-1" onclick="takePhoto()">
                      <img src="/lendables/logo_photo_laptop_600.png" alt="Camera" style="width: 100px; height: auto;" class="me-2">Take Photo
                    </button>
                    <button type="button" class="btn btn-outline-success btn-sm mobile-qr-btn p-1" onclick="showQRCode()">
                      <img src="/lendables/logo_photo_phone_600.png" alt="Mobile" style="width: 100px; height: auto;" class="me-2">Use Phone+QR
                    </button>
                  </div>

                  <!-- Hidden file inputs -->
                  <input type="file" class="d-none" id="itemImage" name="images" 
                         accept="image/*" multiple onchange="handleImageUpload(this)">
                  <input type="file" class="d-none" id="cameraCapture" 
                         accept="image/*" capture="environment" onchange="handleImageUpload(this)">
                  
                  <!-- Paste area -->
                  <div id="pasteArea" class="border border-dashed rounded p-3 text-center mb-3" 
                       style="display: none; background-color: #f8f9fa; cursor: pointer;"
                       tabindex="0">
                    <i class="fas fa-clipboard-check text-info mb-2"></i>
                    <p class="mb-0 text-muted small">Click here and paste an image (Ctrl+V / Cmd+V)</p>
                  </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 class="alert alert-success d-flex align-items-center mb-3 p-2">
                    <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" 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 (initially hidden) -->
                  <div id="rentalOptions" style="display: none;">
                    <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" 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" 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">Available</option>
                    <option value="unavailable">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-primary flex-fill">
                    <i class="fas fa-plus-circle me-2"></i>Create Item
                  </button>
                  <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                    <i class="fas fa-redo me-2"></i>Reset
                  </button>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 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>
      <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">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h5 class="modal-title text-success">
          <i class="fas fa-check-circle me-2"></i>Item Created Successfully!
        </h5>
      </div>
      <div class="modal-body">
        <p class="mb-3">Your item has been added and is now available for the community to borrow.</p>
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-primary" onclick="goToDashboard()">
            <i class="fas fa-tachometer-alt me-1"></i>Back to Dashboard
          </button>
          <button type="button" class="btn btn-outline-success" onclick="createAnother()">
            <i class="fas fa-plus me-1"></i>Create Another
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
.form-label {
  color: #2c3e50;
}

.form-control:focus,
.form-select:focus {
  border-color: #28a745;
  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}

.btn-primary {
  background-color: #28a745;
  border-color: #28a745;
}

.btn-primary:hover {
  background-color: #218838;
  border-color: #1e7e34;
}

.card {
  border-radius: 12px;
}

#imagePreview img {
  border-radius: 8px;
}

.input-group-text {
  background-color: #f8f9fa;
  border-color: #ced4da;
}

.form-text {
  font-size: 0.875rem;
  color: #6c757d;
}

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

.text-danger {
  color: #dc3545 !important;
}
</style>

<!-- QR Code Library -->
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>

<script>
let currentImageFile = null;
let pasteEnabled = false;
let newImageFiles = [];

// Image upload handler for multiple images with primary selection
function handleImageUpload(input) {
  const files = Array.from(input.files);
  console.log('Processing', files.length, 'uploaded files');
  files.forEach(file => addImageToPreview(file));
}

function addImageToPreview(file) {
  const container = document.getElementById('imagePreviewContainer');
  const grid = document.getElementById('imagePreviewGrid');
  
  if (!container || !grid) {
    console.warn('Image preview containers not found');
    return;
  }
  
  // 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);
  
  // Rebuild all previews when adding new images to show/update radio buttons
  setTimeout(() => rebuildImagePreviews(), 10);
  
  container.style.display = 'block';
  disablePasteMode();
}

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="primaryImageIndex" 
                 id="primary${index}" value="${index}" ${index === 0 ? 'checked' : ''}>
          <label class="form-check-label" for="primary${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 = () => removeImageFromPreview(index);
    
    imageCard.appendChild(img);
    imageCard.appendChild(removeBtn);
    grid.appendChild(imageCard);
  });
  
  container.style.display = 'block';
}

function removeImageFromPreview(index) {
  newImageFiles.splice(index, 1);
  rebuildImagePreviews();
  
  if (newImageFiles.length === 0) {
    document.getElementById('imagePreviewContainer').style.display = 'none';
  }
}

// Toggle rental options visibility
function toggleRentalOptions() {
  const checkbox = document.getElementById('enableRental');
  const rentalOptions = document.getElementById('rentalOptions');
  const dailyRateInput = document.getElementById('dailyRate');
  
  if (checkbox.checked) {
    rentalOptions.style.display = 'block';
    dailyRateInput.required = true;
  } else {
    rentalOptions.style.display = 'none';
    dailyRateInput.required = false;
    dailyRateInput.value = '';
    document.getElementById('deposit').value = '';
  }
}

// Image preview functionality
function previewImage(input, source = 'file') {
  const preview = document.getElementById('imagePreview');
  const previewImg = document.getElementById('previewImg');
  const imageSource = document.getElementById('imageSource');
  
  if (input.files && input.files[0]) {
    currentImageFile = input.files[0];
    const reader = new FileReader();
    
    reader.onload = function(e) {
      previewImg.src = e.target.result;
      preview.style.display = 'block';
      imageSource.textContent = `Source: ${source}`;
    };
    
    reader.readAsDataURL(input.files[0]);
  }
}

function previewImageFromBlob(blob, source = 'paste') {
  const preview = document.getElementById('imagePreview');
  const previewImg = document.getElementById('previewImg');
  const imageSource = document.getElementById('imageSource');
  
  // Create a File object from the blob for form submission
  currentImageFile = new File([blob], 'pasted-image.png', { type: blob.type });
  
  const reader = new FileReader();
  reader.onload = function(e) {
    previewImg.src = e.target.result;
    preview.style.display = 'block';
    imageSource.textContent = `Source: ${source}`;
  };
  reader.readAsDataURL(blob);
}

function previewImageFromUrl(imageUrl, source = 'mobile camera') {
  const preview = document.getElementById('imagePreview');
  const previewImg = document.getElementById('previewImg');
  const imageSource = document.getElementById('imageSource');
  
  previewImg.src = imageUrl;
  preview.style.display = 'block';
  imageSource.textContent = `Source: ${source}`;
  
  // For URL-based images, we'll handle the file reference differently in form submission
  currentImageFile = null; // Will be handled by window.mobileUploadedImages
}

function removeImage() {
  // Legacy function - clear everything
  newImageFiles = [];
  document.getElementById('itemImage').value = '';
  document.getElementById('cameraCapture').value = '';
  document.getElementById('imagePreviewContainer').style.display = 'none';
  disablePasteMode();
}

// File upload trigger
function triggerFileUpload() {
  document.getElementById('itemImage').click();
}

// Camera capture trigger
function triggerCamera() {
  document.getElementById('cameraCapture').click();
}

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
            fallbackFileInput();
        });
        
        // Capture button functionality
        captureBtn.addEventListener('click', function() {
            const context = canvas.getContext('2d');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0);
            
            canvas.toBlob(function(blob) {
                const file = new File([blob], `camera-capture-${Date.now()}.jpg`, { type: 'image/jpeg' });
                addImageToPreview(file);
                
                // Stop camera and close modal
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
                modal.hide();
                
                console.log('Camera photo captured and added to preview');
            }, 'image/jpeg', 0.8);
        });
        
        // Clean up when modal is closed
        cameraModal.addEventListener('hidden.bs.modal', function() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            document.body.removeChild(cameraModal);
        });
        
    } else {
        // Fallback for browsers without getUserMedia
        fallbackFileInput();
    }
}

function fallbackFileInput() {
    console.log('Using fallback file input for camera');
    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);
        }
        document.body.removeChild(input);
    };
    
    document.body.appendChild(input);
    input.click();
}

// Paste functionality
function enablePasteMode() {
  console.log('enablePasteMode called');
  const pasteArea = document.getElementById('pasteArea');
  const pasteButton = document.getElementById('pasteButton');
  const pasteButtonText = document.getElementById('pasteButtonText');
  
  if (!pasteArea) {
    console.error('pasteArea element not found');
    return;
  }
  
  console.log('Making paste area visible');
  pasteArea.style.display = 'block';
  pasteEnabled = true;
  pasteArea.focus();
  
  // Change button appearance and text
  pasteButton.classList.remove('btn-outline-success');
  pasteButton.classList.add('btn-success');
  pasteButton.style.backgroundColor = '#198754';
  pasteButton.style.color = 'white';
  pasteButtonText.textContent = 'Paste Image Here';
  
  // Add visual feedback
  pasteArea.style.borderColor = '#0dcaf0';
  pasteArea.style.backgroundColor = '#e7f3ff';
}

function disablePasteMode() {
  const pasteArea = document.getElementById('pasteArea');
  pasteArea.style.display = 'none';
  pasteEnabled = false;
}

// Paste event handlers
document.addEventListener('paste', function(e) {
  if (!pasteEnabled) return;
  
  e.preventDefault();
  const items = e.clipboardData.items;
  
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      console.log('Image found in clipboard');
      
      // Check if we already have 3 images
      if (newImageFiles.length >= 3) {
        alert('Maximum 3 images allowed. Please remove an existing image first.');
        return;
      }
      
      const blob = items[i].getAsFile();
      const timestamp = Date.now();
      const file = new File([blob], `pasted-image-${timestamp}.png`, { type: blob.type });
      addImageToPreview(file);
      
      // Reset button appearance
      const pasteButton = document.getElementById('pasteButton');
      const pasteButtonText = document.getElementById('pasteButtonText');
      if (pasteButton && pasteButtonText) {
        pasteButton.classList.remove('btn-info');
        pasteButton.classList.add('btn-outline-success');
        pasteButton.style.backgroundColor = 'white';
        pasteButton.style.color = '#198754';
        pasteButtonText.textContent = 'Click to Paste Image';
      }
      
      disablePasteMode();
      break;
    }
  }
});

document.getElementById('pasteArea').addEventListener('click', function() {
  this.focus();
});

// Add right-click context menu support for paste area
document.getElementById('pasteArea').addEventListener('contextmenu', function(e) {
  e.preventDefault();
  this.focus();
  console.log('Right-click detected, focusing paste area');
  // Show a temporary hint for the user
  const hint = document.createElement('div');
  hint.textContent = 'Use Ctrl+V or Cmd+V to paste an image';
  hint.className = 'alert alert-info small mt-2';
  hint.style.position = 'absolute';
  hint.style.zIndex = '1000';
  this.appendChild(hint);
  setTimeout(() => hint.remove(), 2000);
});

// QR Code generation function
window.generateQRCode = async function(qrContainer, size = 256, itemId = null, userId = null) {
    console.log('=== QR GENERATION v4.0 STARTED ===');
    
    if (!qrContainer) {
        qrContainer = document.getElementById('qrcode');
        if (!qrContainer) {
            console.error('QR container not found');
            return;
        }
    }
    
    try {
        // For create-item, we use a generic mobile camera URL
        const baseUrl = window.location.origin;
        const qrUrl = `${baseUrl}/mobile-camera?action=create-item`;
        
        console.log('Generating QR for URL:', qrUrl);
        
        // Clear container
        qrContainer.innerHTML = '';
        
        // Generate QR code
        await QRCode.toCanvas(qrContainer, qrUrl, {
            width: size,
            margin: 2,
            color: {
                dark: '#000000',
                light: '#FFFFFF'
            }
        });
        
        console.log('✓ QR code generated 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>
        `;
    }
};

// QR Code functionality
async function showQRCode() {
  const modal = new bootstrap.Modal(document.getElementById('qrModal'));
  const qrContainer = document.getElementById('qrcode');
  
  // Clear previous QR code
  qrContainer.innerHTML = '';
  
  // Generate time-limited QR code for mobile uploads
  try {
    await generateQRCode(qrContainer, 256, null, 41); // Use new session-based QR system
  } catch (error) {
    console.error('QR Code generation failed:', error);
    qrContainer.innerHTML = '<p class="text-danger">QR generation error: ' + error.message + '</p>';
  }
  
  modal.show();
  
  // Listen for mobile uploads
  startListeningForMobileUpload();
}

let mobileUploadInterval;

function startListeningForMobileUpload() {
  // Poll for mobile uploads every 2 seconds
  mobileUploadInterval = setInterval(async () => {
    try {
      const response = await fetch('/api/mobile-upload-status');
      const data = await response.json();
      
      if (data.hasUpload) {
        // Close QR modal
        bootstrap.Modal.getInstance(document.getElementById('qrModal')).hide();
        
        // Get uploaded image(s)
        const imageResponse = await fetch('/api/mobile-upload-image');
        
        if (imageResponse.headers.get('content-type')?.includes('application/json')) {
          // Multi-image response
          const imageData = await imageResponse.json();
          console.log('Multi-image upload detected:', imageData);
          
          // Add mobile images to preview system
          if (imageData.filenames && imageData.filenames.length > 0) {
            for (const filename of imageData.filenames) {
              const imageUrl = `/lendable_items/${filename}`;
              
              // Convert mobile upload to File object for preview system
              try {
                const response = await fetch(imageUrl);
                const blob = await response.blob();
                const file = new File([blob], filename, { type: blob.type });
                addImageToPreview(file);
                console.log('Added mobile image to preview:', filename);
              } catch (error) {
                console.warn('Failed to load mobile image:', filename, error);
              }
            }
            
            // Store filenames for form submission backup
            window.mobileUploadedImages = imageData.filenames;
            console.log('Mobile images added to preview system:', imageData.filenames.length);
          }
        } else {
          // Single image blob response (legacy)
          const blob = await imageResponse.blob();
          const file = new File([blob], 'mobile-camera.jpg', { type: blob.type });
          addImageToPreview(file);
          console.log('Added mobile camera image to preview');
        }
        
        // Don't clear uploads yet - allow more sequential uploads
        clearInterval(mobileUploadInterval);
      }
    } catch (error) {
      console.error('Error checking mobile upload:', error);
    }
  }, 2000);
}

// Clean up interval when modal is closed
document.getElementById('qrModal').addEventListener('hidden.bs.modal', function() {
  if (mobileUploadInterval) {
    clearInterval(mobileUploadInterval);
  }
});

// Handle camera capture
document.getElementById('cameraCapture').addEventListener('change', function() {
  handleImageUpload(this);
});

// Form handling
let isCreating = false; // Prevent multiple submissions

document.getElementById('createItemForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  
  // Prevent multiple simultaneous submissions
  if (isCreating) {
    console.log('Form already submitting, ignoring duplicate submission');
    return;
  }
  
  isCreating = true;
  console.log('Form submission started');
  
  const submitBtn = this.querySelector('button[type="submit"]');
  const originalText = submitBtn.innerHTML;
  
  // Show loading state
  submitBtn.disabled = true;
  submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Creating...';
  
  try {
    const formData = new FormData(this);
    
    // Debug: Log form data
    console.log('Form data entries:');
    for (let [key, value] of formData.entries()) {
      console.log(key, value);
    }
    
    // Add new images from the preview system
    console.log('Preparing form submission with', newImageFiles.length, 'new images');
    newImageFiles.forEach((file, index) => {
      formData.append('images', 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="primaryImageIndex"]:checked');
    if (selectedPrimary && newImageFiles.length > 1) {
      formData.append('primaryImageIndex', selectedPrimary.value);
      console.log('Selected primary image index:', selectedPrimary.value);
    }
    
    // Handle mobile uploaded images from sequential uploads (prioritize these over preview images)
    if (window.mobileUploadedImages && window.mobileUploadedImages.length > 0) {
      formData.set('mobileUploadedImages', JSON.stringify(window.mobileUploadedImages));
      formData.append('hasMobileUploads', 'true');
      console.log('Including mobile uploaded images in form:', window.mobileUploadedImages);
    }
    
    console.log('Sending POST request to /api/items');
    const response = await fetch('/api/items', {
      method: 'POST',
      body: formData
    });
    
    console.log('Response received:', response.status, response.statusText);
    
    // Handle authentication errors by redirecting to login
    if (response.status === 401) {
      console.log('Authentication required - redirecting to login');
      window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
      return;
    }
    
    if (response.ok) {
      const item = await response.json();
      
      // Clear mobile uploads after successful creation
      await fetch('/api/mobile-upload-complete', { method: 'POST' });
      
      // Show success alert and redirect to browse page
      Swal.fire({
        title: 'Item Created Successfully!',
        text: `Your item "${item.name || item.title}" has been added to the marketplace.`,
        icon: 'success',
        confirmButtonText: 'View All Items',
        confirmButtonColor: '#28a745',
        timer: 2000,
        timerProgressBar: true
      }).then((result) => {
        // Always redirect to browse page to show new item at top
        window.location.href = '/browse?newest=true';
      });
    } else {
      let errorMessage = 'Unknown error occurred';
      try {
        const errorData = await response.json();
        errorMessage = errorData.error || errorData.message || 'Server error';
      } catch {
        errorMessage = await response.text() || 'Server returned an error';
      }
      
      Swal.fire({
        title: 'Error Creating Item',
        text: errorMessage,
        icon: 'error',
        confirmButtonText: 'Try Again',
        confirmButtonColor: '#dc3545'
      });
    }
  } catch (error) {
    console.error('Error:', error);
    Swal.fire({
      title: 'Network Error',
      text: 'Unable to connect to server. Please check your connection and try again.',
      icon: 'error',
      confirmButtonText: 'Try Again',
      confirmButtonColor: '#dc3545'
    });
  } finally {
    // Re-enable form submission and restore button state
    isCreating = false;
    submitBtn.disabled = false;
    submitBtn.innerHTML = originalText;
  }
});

function resetForm() {
  document.getElementById('createItemForm').reset();
  removeImage();
  newImageFiles = [];
  const container = document.getElementById('imagePreviewContainer');
  if (container) container.style.display = 'none';
}

function goToDashboard() {
  window.location.href = '/browse';
}

function createAnother() {
  bootstrap.Modal.getInstance(document.getElementById('successModal')).hide();
  resetForm();
}

// Auto-resize textarea
document.getElementById('description').addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight + 'px';
});

// Form validation feedback
document.querySelectorAll('input[required], select[required], textarea[required]').forEach(field => {
  field.addEventListener('blur', function() {
    if (!this.value.trim()) {
      this.classList.add('is-invalid');
    } else {
      this.classList.remove('is-invalid');
    }
  });
  
  field.addEventListener('input', function() {
    if (this.value.trim()) {
      this.classList.remove('is-invalid');
    }
  });
});
</script>
{% endblock %}