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

{% block title %}Respond to Borrow Request - LocalLendables{% endblock %}

{% block content %}
<!-- Breadcrumbs below header -->
<div class="container-fluid" style="background-color: #f8f9fa; padding: 0.25rem 0; margin-top: 0;">
  <div class="row">
    <div class="col-12">
      <nav aria-label="breadcrumb" style="margin-left: 50px;">
        <ol class="breadcrumb tiny mb-0" style="background: transparent;">
          {% for breadcrumb in breadcrumbs %}
            {% if loop.last %}
              <li class="breadcrumb-item active" aria-current="page">{{ breadcrumb.name }}</li>
            {% else %}
              <li class="breadcrumb-item">
                {% if breadcrumb.url %}
                  <a href="{{ breadcrumb.url }}">{{ breadcrumb.name }}</a>
                {% else %}
                  {{ breadcrumb.name }}
                {% endif %}
              </li>
            {% endif %}
          {% endfor %}
        </ol>
      </nav>
    </div>
  </div>
</div>

<div class="container-fluid px-3 py-4">
  <div class="row">
    <div class="col-md-8 mx-auto">
      <!-- Header with Owner Avatar -->
      <div class="mb-4">
        <div class="d-flex align-items-center">
          {% if currentUser.avatar %}
            <img src="/lendables/{{ currentUser.avatar }}" 
                 alt="{{ currentUser.firstName }}" 
                 class="rounded-circle me-3" 
                 style="width: 50px; height: 50px; object-fit: cover; border: 2px solid #ddd;">
          {% else %}
            <div class="rounded-circle me-3 bg-secondary d-flex align-items-center justify-content-center" 
                 style="width: 50px; height: 50px; border: 2px solid #ddd;">
              <i class="fas fa-user text-white"></i>
            </div>
          {% endif %}
          <h2 class="mb-0"><i class="fas fa-handshake me-2"></i>Borrow Request</h2>
        </div>
      </div>

      <!-- Request Details Card -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Request Details</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-4">
              {% if item.primaryLogo %}
                <img src="/lendable_items/{{ item.primaryLogo }}" 
                     alt="{{ item.name }}" 
                     class="img-fluid rounded shadow-sm">
              {% else %}
                <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 200px;">
                  <i class="fas fa-image text-muted fa-3x"></i>
                </div>
              {% endif %}
            </div>
            <div class="col-md-8">
              <h4>{{ item.name }}</h4>
              <p class="text-muted">{{ item.description }}</p>
              
              <div class="row mt-3">
                <div class="col-sm-6">
                  <strong>Requested by:</strong><br>
                  <div class="d-flex align-items-center mt-1">
                    {% if borrower.avatar %}
                      <img src="/lendables/{{ borrower.avatar }}" 
                           alt="{{ borrower.firstName }}" 
                           class="rounded-circle me-2" 
                           style="width: 50px; height: 50px; object-fit: cover; border: 2px solid #ddd;" 
                           onerror="this.src='/lendables/default-placeholder.jpg'">
                    {% else %}
                      <div class="rounded-circle me-2 bg-secondary d-flex align-items-center justify-content-center" 
                           style="width: 50px; height: 50px; color: white; font-weight: bold;">
                        {{ (borrower.showName ?: (borrower.firstName ~ ' ' ~ borrower.lastName))|first|upper }}{{ (borrower.showName ?: (borrower.firstName ~ ' ' ~ borrower.lastName))|split(' ')|last|first|upper }}
                      </div>
                    {% endif %}
                    <span class="fw-semibold">{{ borrower.showName ?: (borrower.firstName ~ (borrower.lastName ? ' ' ~ borrower.lastName : '')) }}</span>
                  </div>
                </div>
                <div class="col-sm-6">
                  <strong>Request Date:</strong><br>
                  <span class="text-muted">{{ borrowRequest.createdAt|date('M j, Y') }}</span>
                </div>
              </div>

              <div class="row mt-3">
                <div class="col-sm-6">
                  <strong>Start Date:</strong><br>
                  <span class="text-muted">{{ borrowRequest.startDate|date('M j, Y') }}</span>
                </div>
                <div class="col-sm-6">
                  <strong>End Date:</strong><br>
                  <span class="text-muted">{{ borrowRequest.endDate|date('M j, Y') }}</span>
                </div>
              </div>

              <!-- Calendar View -->
              <div class="mt-4">
                <strong>Loan Duration Calendar:</strong>
                <div id="calendar" class="mt-2"></div>
              </div>

              {% if borrowRequest.message %}
                <div class="mt-3">
                  <div class="d-flex align-items-center mb-2">
                    <strong>Message from </strong>
                    {% if borrower.avatar %}
                      <img src="/lendables/{{ borrower.avatar }}" 
                           alt="{{ borrower.firstName }}" 
                           class="rounded-circle mx-2" 
                           style="width: 24px; height: 24px; object-fit: cover; border: 1px solid #ddd;" 
                           onerror="this.style.display='none'">
                    {% else %}
                      <div class="rounded-circle mx-2 bg-secondary d-flex align-items-center justify-content-center" 
                           style="width: 24px; height: 24px; color: white; font-weight: bold; font-size: 10px;">
                        {{ (borrower.showName ?: (borrower.firstName ~ ' ' ~ borrower.lastName))|first|upper }}{{ (borrower.showName ?: (borrower.firstName ~ ' ' ~ borrower.lastName))|split(' ')|last|first|upper }}
                      </div>
                    {% endif %}
                    <strong>{{ borrower.showName ?: (borrower.firstName ~ (borrower.lastName ? ' ' ~ borrower.lastName : '')) }}:</strong>
                  </div>
                  <div class="bg-light p-3 rounded">
                    {{ borrowRequest.message }}
                  </div>
                </div>
              {% endif %}
              
              {% if borrowRequest.audioFilename %}
                <div class="mt-3">
                  <strong>Audio message from {{ borrower.firstName }}:</strong>
                  <div class="bg-light p-3 rounded mt-2">
                    <div class="d-flex align-items-center mb-2">
                      <i class="fas fa-microphone me-2 text-primary"></i>
                      <small class="text-muted">Audio recording</small>
                    </div>
                    <audio controls style="width: 100%; max-width: 400px;">
                      <source src="/temp/uploads/{{ borrowRequest.audioFilename }}" type="audio/webm">
                      <source src="/temp/uploads/{{ borrowRequest.audioFilename }}" type="audio/wav">
                      Your browser does not support the audio element.
                    </audio>
                    {% if borrowRequest.transcription %}
                      <div class="mt-3 pt-2 border-top">
                        <small class="text-muted d-block mb-1">
                          <i class="fas fa-file-alt me-1"></i>Transcription:
                        </small>
                        <div class="fst-italic">{{ borrowRequest.transcription }}</div>
                      </div>
                    {% else %}
                      <div class="mt-2">
                        <small class="text-muted">
                          <i class="fas fa-info-circle me-1"></i>Transcription will be available after processing
                        </small>
                      </div>
                    {% endif %}
                  </div>
                </div>
              {% endif %}
            </div>
          </div>
        </div>
      </div>

      <!-- Response Form -->
      <div class="card">
        <div class="card-header bg-success text-white">
          <h5 class="mb-0"><i class="fas fa-reply me-2"></i>Your Response</h5>
        </div>
        <div class="card-body">
          <form id="responseForm">
            <input type="hidden" name="requestId" value="{{ borrowRequest.id }}" id="requestIdField">
            
            <!-- Response Type -->
            <a name="your-decision"></a>
            <div class="mb-4">
              <label class="form-label"><strong>Your Decision:</strong></label>
              <div class="row">
                <div class="col-md-4">
                  <div class="card response-option" data-response="approved" style="border: 2px solid #28a745 !important; background-color: white !important;">
                    <div class="card-body text-center py-4">
                      <i class="fas fa-check-circle text-success fa-3x mb-3"></i>
                      <h5 class="mb-2">Approve</h5>
                      <small style="font-size: 0.75rem !important; line-height: 0.8 !important; margin: 0 !important; padding: 0 !important; display: block !important;">Accept as requested</small>
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="card response-option" data-response="counter" style="border: 2px solid #ffc107 !important; background-color: white !important;">
                    <div class="card-body text-center py-4">
                      <i class="fas fa-edit text-warning fa-3x mb-3"></i>
                      <h5 class="mb-2">Other Options</h5>
                      <small style="font-size: 0.75rem !important; line-height: 0.8 !important; margin: 0 !important; padding: 0 !important; display: block !important;">Alternative Proposal</small>
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="card response-option" data-response="rejected" style="border: 2px solid #dc3545 !important; background-color: white !important;">
                    <div class="card-body text-center py-4">
                      <i class="fas fa-times-circle text-danger fa-3x mb-3"></i>
                      <h5 class="mb-2">Decline</h5>
                      <small style="font-size: 0.75rem !important; line-height: 0.8 !important; margin: 0 !important; padding: 0 !important; display: block !important;">Not available</small>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Counter Offer Dates (hidden by default) -->
            <div id="counterOfferSection" style="display: none;">
              <div class="row mb-3">
                <div class="col-md-6">
                  <label for="newStartDate" class="form-label">Alternative Start Date</label>
                  <input type="date" class="form-control" id="newStartDate" name="newStartDate">
                </div>
                <div class="col-md-6">
                  <label for="newEndDate" class="form-label">Alternative End Date</label>
                  <input type="date" class="form-control" id="newEndDate" name="newEndDate">
                </div>
              </div>
            </div>

            <!-- Response Message -->
            <div class="mb-3">
              <label for="responseMessage" class="form-label">Message to Borrower</label>
              
              <!-- Convenience paste labels - only show if owner data exists -->
              <div class="mb-2 d-flex flex-wrap align-items-center gap-2">
                <strong>Add:</strong>
                {% if owner.phone %}
                  <small class="badge text-dark border" 
                         style="cursor: pointer; font-size: 0.7rem; background-color: #d4edda;" 
                         onclick="pasteContactInfo('phone', ' {{ owner.phone }} ')" 
                         title="Click to paste your phone number">
                    phone #
                  </small>
                {% endif %}
                
                {% if owner.email %}
                  <small class="badge text-dark border" 
                         style="cursor: pointer; font-size: 0.7rem; background-color: #d4edda;" 
                         onclick="pasteContactInfo('email', ' {{ owner.email }} ')" 
                         title="Click to paste your email address">
                    email
                  </small>
                {% endif %}
                
                {% if owner.address or owner.town %}
                  <small class="badge text-dark border" 
                         style="cursor: pointer; font-size: 0.7rem; background-color: #d4edda;" 
                         onclick="pasteContactInfo('address', ' {{ owner.address }}{% if owner.town %}, {{ owner.town }}{% endif %} ')" 
                         title="Click to paste your address">
                    address
                  </small>
                {% endif %}
                
                {% if owner.firstName and owner.lastName %}
                  <small class="badge text-dark border" 
                         style="cursor: pointer; font-size: 0.7rem; background-color: #d4edda;" 
                         onclick="pasteContactInfo('name', ' {{ owner.firstName }} {{ owner.lastName }} ')" 
                         title="Click to paste your full name">
                    full name
                  </small>
                {% endif %}
              </div>
              
              <textarea class="form-control" id="responseMessage" name="responseMessage" rows="4" 
                        placeholder="Add a message for the borrower..."></textarea>
              
              <!-- Audio Response -->
              <div class="mt-2">
                <button type="button" class="btn btn-outline-primary btn-sm" id="recordBtn">
                  <i class="fas fa-microphone me-1"></i>Record Audio Response
                </button>
                <div id="audioControls" style="display: none;" class="mt-2">
                  <button type="button" class="btn btn-sm btn-danger" id="stopBtn">
                    <i class="fas fa-stop me-1"></i>Stop Recording
                  </button>
                  <span id="recordingTime" class="ms-2 text-muted">00:00</span>
                </div>
                <div id="audioPlayback" style="display: none;" class="mt-2">
                  <audio controls class="w-100"></audio>
                  <div class="mt-1">
                    <button type="button" class="btn btn-sm btn-success" id="useAudioBtn">
                      <i class="fas fa-check me-1"></i>Use This Recording
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="retryBtn">
                      <i class="fas fa-redo me-1"></i>Try Again
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- Pricing (for approved requests) -->
            <div id="pricingSection" style="display: none;">
              {% if item.pricePerDay and item.pricePerDay > 0 %}
              <div class="row mb-3">
                <div class="col-md-6">
                  <label for="dailyRate" class="form-label">Daily Rate ($)</label>
                  <input type="number" class="form-control" id="dailyRate" name="dailyRate" 
                         step="0.01" min="0" placeholder="{{ item.pricePerDay }}" value="{{ item.pricePerDay }}">
                  <small class="text-muted">Current rate: ${{ item.pricePerDay }}/day</small>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Total Amount</label>
                  <div class="form-control-plaintext" id="totalAmount">$0.00</div>
                </div>
              </div>
              {% else %}
              <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>This item is available for free lending.
              </div>
              {% endif %}
            </div>

            <!-- Submit Buttons -->
            <div class="d-flex justify-content-end gap-2">
              <a href="/dashboard/{{ currentUser.id }}" class="btn btn-secondary">Cancel</a>
              <button type="submit" class="btn btn-primary" id="submitBtn">
                <i class="fas fa-paper-plane me-2"></i>Send Response
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Chat History -->
      {% if chatHistory and chatHistory|length > 0 %}
      <div class="card mt-4">
        <div class="card-header">
          <h5 class="mb-0"><i class="fas fa-comments me-2"></i>Chat History</h5>
        </div>
        <div class="card-body">
          <div class="chat-messages" style="max-height: 300px; overflow-y: auto;">
            {% for message in chatHistory %}
              <div class="d-flex mb-3 {% if message.senderId == currentUser.id %}justify-content-end{% endif %}">
                <div class="message-bubble {% if message.senderId == currentUser.id %}bg-primary text-white{% else %}bg-light{% endif %} p-3 rounded">
                  <div class="message-content">{{ message.textContent }}</div>
                  <small class="{% if message.senderId == currentUser.id %}text-white-50{% else %}text-muted{% endif %}">
                    {{ message.createdAt|date('M j, g:i A') }}
                  </small>
                </div>
              </div>
            {% endfor %}
          </div>
        </div>
      </div>
      {% endif %}

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

<!-- Validation Modal -->
<div class="modal fade" id="validationModal" tabindex="-1" aria-labelledby="validationModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header border-0 pb-0">
        <h6 class="modal-title text-warning" id="validationModalLabel">
          <i class="fas fa-exclamation-triangle me-2"></i>Selection Required
        </h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body pt-2">
        <p class="mb-2 small" style="color: #2d5a3d;">Choose Approve, Decline, or Other. The Message to Borrower is recommended but not required.</p>
      </div>
    </div>
  </div>
</div>

<!-- Pre-Sign Modal -->
<div class="modal fade" id="preSignModal" tabindex="-1" aria-labelledby="preSignModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="preSignModalLabel">
          <i class="fas fa-signature me-2"></i>Pre-Sign Loan Agreement?
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="mb-4">
          <div class="alert alert-info">
            <i class="fas fa-info-circle me-2"></i>
            <strong>Streamline the Process:</strong> You can pre-sign your half of the loan agreement now to speed up the borrowing process. After you sign, the borrower will just need to sign their half and the agreement will be complete.
          </div>
        </div>
        
        <div class="mb-3">
          <p><strong>Would you like to pre-sign the loan agreement as the owner?</strong></p>
          <p class="text-muted">This will allow the borrower to complete the process faster by only needing to sign their portion.</p>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Your Full Name (as it appears in your profile)</label>
          <input type="text" class="form-control" id="ownerSignatureName" value="{{ currentUser.firstName ~ ' ' ~ currentUser.lastName }}" readonly>
        </div>
        
        <div class="mb-3">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="confirmOwnerSignature">
            <label class="form-check-label" for="confirmOwnerSignature">
              I hereby electronically sign this loan agreement as the owner with the same legal effect as a handwritten signature.
            </label>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" onclick="skipPreSigning()">
          <i class="fas fa-skip-forward me-2"></i>Skip - Sign Later
        </button>
        <button type="button" class="btn btn-success" id="preSignBtn" onclick="preSignAgreement()">
          <i class="fas fa-signature me-2"></i>Pre-Sign Agreement
        </button>
      </div>
    </div>
  </div>
</div>

<style>
.response-option {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent !important;
}

.response-option:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.15);
}

.response-option.selected {
  border: 3px solid #0d6efd !important;
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(13, 110, 253, 0.3);
  background: linear-gradient(145deg, #f8f9fa, #e9ecef);
}

.response-option.selected .card-body {
  background: rgba(13, 110, 253, 0.05);
  border-radius: 8px;
}

.response-option.selected i {
  transform: scale(1.1);
}

.response-option.selected h6 {
  color: #0d6efd;
  font-weight: bold;
}

.message-bubble {
  max-width: 70%;
  word-wrap: break-word;
}
</style>

<script>
// Contact info paste function
function pasteContactInfo(type, value) {
  const messageTextarea = document.getElementById('responseMessage');
  const currentText = messageTextarea.value;
  
  // Just paste the raw value with spaces, no labels
  const newText = currentText + value;
  
  messageTextarea.value = newText;
  messageTextarea.focus();
}

document.addEventListener('DOMContentLoaded', function() {
let selectedResponse = null;
let mediaRecorder = null;
let audioChunks = [];
let recordingInterval = null;
let recordingStartTime = 0;

const responseOptions = document.querySelectorAll('.response-option');
const submitBtn = document.getElementById('submitBtn');
const counterOfferSection = document.getElementById('counterOfferSection');
const pricingSection = document.getElementById('pricingSection');
const dailyRateInput = document.getElementById('dailyRate');
const totalAmountDisplay = document.getElementById('totalAmount');
const responseForm = document.getElementById('responseForm');

// Form elements initialized successfully

// Handle response option selection
responseOptions.forEach(option => {
  option.addEventListener('click', function() {
    responseOptions.forEach(opt => opt.classList.remove('selected'));
    this.classList.add('selected');
    selectedResponse = this.dataset.response;
    
    // Show/hide sections based on selection
    if (selectedResponse === 'counter') {
      counterOfferSection.style.display = 'block';
      pricingSection.style.display = 'block';
    } else if (selectedResponse === 'approved') {
      counterOfferSection.style.display = 'none';
      pricingSection.style.display = 'block';
    } else {
      counterOfferSection.style.display = 'none';
      pricingSection.style.display = 'none';
    }
    
    // No need to enable/disable button - it stays clickable for validation
  });
});

// Calculate total amount
function calculateTotal() {
  if (!dailyRateInput || !totalAmountDisplay) return;
  
  const dailyRate = parseFloat(dailyRateInput.value) || 0;
  const startDateEl = document.getElementById('newStartDate');
  const endDateEl = document.getElementById('newEndDate');
  
  const startDate = new Date(startDateEl?.value || '{{ borrowRequest.startDate|date('Y-m-d') }}');
  const endDate = new Date(endDateEl?.value || '{{ borrowRequest.endDate|date('Y-m-d') }}');
  
  if (startDate && endDate && endDate > startDate) {
    const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    const total = dailyRate * days;
    totalAmountDisplay.textContent = `$${total.toFixed(2)}`;
  } else {
    totalAmountDisplay.textContent = '$0.00';
  }
}

if (dailyRateInput) dailyRateInput.addEventListener('input', calculateTotal);
const newStartDate = document.getElementById('newStartDate');
const newEndDate = document.getElementById('newEndDate');
if (newStartDate) newStartDate.addEventListener('change', calculateTotal);
if (newEndDate) newEndDate.addEventListener('change', calculateTotal);

// Form submission
if (responseForm) {
  responseForm.addEventListener('submit', async function(e) {
  e.preventDefault();
  if (!selectedResponse) {
    showValidationModal();
    return;
  }
  
  const formData = new FormData(this);
  formData.append('response', selectedResponse);
  
  // Ensure requestId is included
  const requestId = document.getElementById('requestIdField').value;
  if (requestId) {
    formData.set('requestId', requestId);
  }
  
  // Add audio if recorded
  if (this.audioBlob) {
    formData.append('audioResponse', this.audioBlob, 'response.webm');
  }
  
  // Prepare form data for submission
  
  try {
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Sending...';
    
    const response = await fetch('/api/borrow-requests/respond', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        requestId: formData.get('requestId'),
        response: formData.get('response'),
        responseMessage: formData.get('responseMessage'),
        newStartDate: formData.get('newStartDate'),
        newEndDate: formData.get('newEndDate'),
        dailyRate: formData.get('dailyRate')
      })
    });
    
    const result = await response.json();
    
    if (result.success) {
      // Check if pre-signing option should be shown
      if (result.showPreSignOption && result.agreementId && formData.get('response') === 'approved') {
        showPreSignModal(result.agreementId);
      } else {
        window.location.href = '/dashboard/{{ currentUser.id }}?message=Response sent successfully';
      }
    } else {
      alert('Error: ' + result.error);
      submitBtn.disabled = false;
      submitBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Response';
    }
  } catch (error) {
    console.error('Error sending response:', error);
    alert('Failed to send response');
    submitBtn.disabled = false;
    submitBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Response';
  }
  });
} else {
  console.error('responseForm element not found');
}

// Initialize total calculation
calculateTotal();

// Validation modal function
function showValidationModal() {
  const validationModal = new bootstrap.Modal(document.getElementById('validationModal'));
  validationModal.show();
}



// Pre-signing workflow variables
let currentAgreementId = null;

function showPreSignModal(agreementId) {
  currentAgreementId = agreementId;
  const preSignModal = new bootstrap.Modal(document.getElementById('preSignModal'));
  preSignModal.show();
}

window.skipPreSigning = function() {
  const preSignModal = bootstrap.Modal.getInstance(document.getElementById('preSignModal'));
  preSignModal.hide();
  window.location.href = '/dashboard/{{ currentUser.id }}?message=Response sent successfully';
}

window.preSignAgreement = async function() {
  const confirmCheckbox = document.getElementById('confirmOwnerSignature');
  const preSignBtn = document.getElementById('preSignBtn');
  
  if (!confirmCheckbox.checked) {
    LocalLendables.showErrorToast('Signature Required', 'Please check the confirmation box to electronically sign the agreement.');
    return;
  }
  
  if (!currentAgreementId) {
    LocalLendables.showErrorToast('Error', 'Agreement ID not found. Please try again.');
    return;
  }
  
  try {
    preSignBtn.disabled = true;
    preSignBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Signing...';
    
    const response = await fetch(`/api/agreements/${currentAgreementId}/sign`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        signerType: 'owner',
        signature: document.getElementById('ownerSignatureName').value,
        timestamp: new Date().toISOString()
      })
    });
    
    const result = await response.json();
    
    if (result.success) {
      const preSignModal = bootstrap.Modal.getInstance(document.getElementById('preSignModal'));
      preSignModal.hide();
      LocalLendables.showSuccessToast('Agreement Pre-Signed!', 'You have successfully pre-signed the loan agreement. The borrower will be notified to complete their signature.');
      setTimeout(() => {
        window.location.href = '/dashboard/{{ currentUser.id }}?message=Agreement pre-signed successfully';
      }, 2000);
    } else {
      LocalLendables.showErrorToast('Signing Error', result.error || 'Failed to sign agreement');
      preSignBtn.disabled = false;
      preSignBtn.innerHTML = '<i class="fas fa-signature me-2"></i>Pre-Sign Agreement';
    }
  } catch (error) {
    console.error('Error signing agreement:', error);
    LocalLendables.showErrorToast('Connection Error', 'Unable to sign agreement. Please check your connection and try again.');
    preSignBtn.disabled = false;
    preSignBtn.innerHTML = '<i class="fas fa-signature me-2"></i>Pre-Sign Agreement';
  }
}

// Calendar implementation
function generateCalendar() {
  const calendarEl = document.getElementById('calendar');
  if (!calendarEl) {
    console.log('Calendar element not found');
    return;
  }
  
  const startDate = new Date('{{ borrowRequest.startDate|date('Y-m-d') }}');
  const endDate = new Date('{{ borrowRequest.endDate|date('Y-m-d') }}');
  
  console.log('Start date details:', startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
  console.log('End date details:', endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
  
  console.log('Calendar dates:', { startDate, endDate });
  
  // Determine calendar month range (start month to end month)
  const startMonth = new Date(startDate.getFullYear(), startDate.getMonth(), 1);
  const endMonth = new Date(endDate.getFullYear(), endDate.getMonth(), 1);
  
  let html = '<div class="calendar-container">';
  
  // Generate calendars for each month in the range
  let currentMonth = new Date(startMonth);
  while (currentMonth <= endMonth) {
    html += generateMonthCalendar(currentMonth, startDate, endDate);
    currentMonth.setMonth(currentMonth.getMonth() + 1);
  }
  
  html += '</div>';
  html += '<small class="text-muted mt-2 d-block"><span class="bg-warning px-1">■</span> Requested loan period</small>';
  
  calendarEl.innerHTML = html;
}

function generateMonthCalendar(monthDate, startDate, endDate) {
  const year = monthDate.getFullYear();
  const month = monthDate.getMonth();
  const monthName = monthDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
  
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const firstDayOfWeek = firstDay.getDay();
  
  let html = `<div class="month-calendar mb-3">`;
  html += `<div class="text-center mb-2 fw-bold">${monthName}</div>`;
  html += `<div class="calendar-grid" style="display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; border: 1px solid #dee2e6;">`;
  
  // Days of week header
  const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  daysOfWeek.forEach(day => {
    html += `<div class="text-center fw-bold p-2 small bg-light">${day}</div>`;
  });
  
  // Empty cells for days before month start
  for (let i = 0; i < firstDayOfWeek; i++) {
    html += '<div class="p-2 bg-light"></div>';
  }
  
  // Month days
  for (let day = 1; day <= lastDay.getDate(); day++) {
    const currentDate = new Date(year, month, day);
    
    // Extract actual dates from template values using string parsing
    const startDateStr = '{{ borrowRequest.startDate|date('Y-m-d') }}';
    const endDateStr = '{{ borrowRequest.endDate|date('Y-m-d') }}';
    const [startYear, startMonthStr, startDayStr] = startDateStr.split('-');
    const [endYear, endMonthStr, endDayStr] = endDateStr.split('-');
    const startDay = parseInt(startDayStr);
    const startMonth = parseInt(startMonthStr) - 1; // Convert to 0-indexed
    const endDay = parseInt(endDayStr);
    const endMonth = parseInt(endMonthStr) - 1; // Convert to 0-indexed
    
    let isInRange = false;
    if (year === parseInt(startYear) && month === startMonth && year === parseInt(endYear) && month === endMonth) {
      // Same month - check if day is between start and end (inclusive)
      isInRange = day >= startDay && day <= endDay;
    } else if (year === parseInt(startYear) && month === startMonth) {
      // Start month - from start day to end of month
      isInRange = day >= startDay;
    } else if (year === parseInt(endYear) && month === endMonth) {
      // End month - from start of month to end day
      isInRange = day <= endDay;
    } else if ((year > parseInt(startYear) || (year === parseInt(startYear) && month > startMonth)) &&
               (year < parseInt(endYear) || (year === parseInt(endYear) && month < endMonth))) {
      // Middle months - all days
      isInRange = true;
    }
    
    const isToday = currentDate.toDateString() === new Date().toDateString();
    
    let classes = 'text-center p-2 small';
    let bgClass = 'bg-white';
    
    if (isInRange) {
      bgClass = 'bg-warning';
      classes += ' fw-bold';
    }
    if (isToday) {
      classes += ' border border-primary';
    }
    
    html += `<div class="${classes} ${bgClass}" style="min-height: 35px; display: flex; align-items: center; justify-content: center;">${day}</div>`;
  }
  
  html += '</div></div>';
  return html;
}

// Audio recording functionality
const recordBtn = document.getElementById('recordBtn');
const stopBtn = document.getElementById('stopBtn');
const audioControls = document.getElementById('audioControls');
const audioPlayback = document.getElementById('audioPlayback');
const useAudioBtn = document.getElementById('useAudioBtn');
const retryBtn = document.getElementById('retryBtn');
const recordingTimeDisplay = document.getElementById('recordingTime');

if (recordBtn) recordBtn.addEventListener('click', startRecording);
if (stopBtn) stopBtn.addEventListener('click', stopRecording);
if (useAudioBtn) useAudioBtn.addEventListener('click', useAudioRecording);
if (retryBtn) retryBtn.addEventListener('click', retryRecording);

async function startRecording() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder = new MediaRecorder(stream);
    audioChunks = [];
    
    mediaRecorder.ondataavailable = event => {
      audioChunks.push(event.data);
    };
    
    mediaRecorder.onstop = () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
      const audioUrl = URL.createObjectURL(audioBlob);
      const audioElement = audioPlayback.querySelector('audio');
      audioElement.src = audioUrl;
      audioElement.audioBlob = audioBlob;
      
      audioPlayback.style.display = 'block';
      audioControls.style.display = 'none';
      recordBtn.style.display = 'inline-block';
    };
    
    mediaRecorder.start();
    recordBtn.style.display = 'none';
    audioControls.style.display = 'block';
    audioPlayback.style.display = 'none';
    
    // Start timer
    recordingStartTime = Date.now();
    recordingInterval = setInterval(updateRecordingTime, 1000);
    
  } catch (error) {
    console.error('Error accessing microphone:', error);
    alert('Unable to access microphone. Please check permissions.');
  }
}

function stopRecording() {
  if (mediaRecorder && mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop();
    mediaRecorder.stream.getTracks().forEach(track => track.stop());
    clearInterval(recordingInterval);
  }
}

function updateRecordingTime() {
  const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
  const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
  const seconds = (elapsed % 60).toString().padStart(2, '0');
  recordingTimeDisplay.textContent = `${minutes}:${seconds}`;
}

function useAudioRecording() {
  const audioElement = audioPlayback.querySelector('audio');
  if (audioElement.audioBlob) {
    // Store the audio blob for form submission
    document.getElementById('responseForm').audioBlob = audioElement.audioBlob;
    document.getElementById('responseMessage').value = '[Audio response recorded]';
    alert('Audio response will be sent with your response.');
  }
}

function retryRecording() {
  audioPlayback.style.display = 'none';
  recordBtn.style.display = 'inline-block';
  recordingTimeDisplay.textContent = '00:00';
}

// Initialize calendar when page loads
generateCalendar();

}); // End DOMContentLoaded
</script>
{% endblock %}