<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Active Loans - LocalLendables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .loan-card {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        
        .loan-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: bold;
        }
        
        .status-reserved {
            background: linear-gradient(135deg, #ffc107, #fd7e14);
            color: white;
        }
        
        .status-active {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }
        
        .status-return-requested {
            background: linear-gradient(135deg, #17a2b8, #6f42c1);
            color: white;
        }
        
        .action-btn {
            border-radius: 25px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .timeline-item {
            position: relative;
            padding-left: 2rem;
            margin-bottom: 1rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0.5rem;
            width: 0.75rem;
            height: 0.75rem;
            border-radius: 50%;
            background: #28a745;
        }
        
        .timeline-item.completed::before {
            background: #28a745;
        }
        
        .timeline-item.current::before {
            background: #ffc107;
            animation: pulse 2s infinite;
        }
        
        .timeline-item.pending::before {
            background: #6c757d;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
            100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
        }
    </style>
</head>
<body class="bg-light">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container">
            <a class="navbar-brand fw-bold" href="/dashboard/{{ currentUser.id }}">
                <i class="fas fa-leaf me-2"></i>LocalLendables
            </a>
            <div class="d-flex align-items-center text-white">
                <span class="me-3">Welcome, {{ currentUser.firstName }}!</span>
                <a href="/dashboard/{{ currentUser.id }}" class="btn btn-outline-light btn-sm">
                    <i class="fas fa-home me-1"></i>Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-handshake me-2 text-primary"></i>My Active Loans
            </h2>
            <div class="d-flex gap-2">
                <a href="/rewards" class="btn btn-primary">
                    <i class="fas fa-star me-1"></i>Rewards
                </a>
                <a href="/browse" class="btn btn-success">
                    <i class="fas fa-search me-1"></i>Browse Items
                </a>
                <a href="/help" class="btn btn-info">
                    <i class="fas fa-question-circle me-1"></i>Help
                </a>
            </div>
        </div>

        {% if activeLoans|length > 0 %}
            <div class="row">
                {% for loan in activeLoans %}
                <div class="col-md-6 mb-4">
                    <div class="card loan-card h-100">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">{{ loan.item_name }}</h5>
                            <span class="status-badge status-{{ loan.status|replace('_', '-') }}">
                                {% if loan.status == 'reserved' %}
                                    <i class="fas fa-clock me-1"></i>Agreement Signed
                                {% elseif loan.status == 'active' %}
                                    <i class="fas fa-check-circle me-1"></i>Active Loan
                                {% elseif loan.status == 'return_requested' %}
                                    <i class="fas fa-undo me-1"></i>Return Requested
                                {% endif %}
                            </span>
                        </div>
                        <div class="card-body">
                            <!-- Loan Details -->
                            <div class="mb-3">
                                <div class="row text-sm">
                                    <div class="col-6">
                                        <strong>Role:</strong> {{ loan.user_role|title }}
                                    </div>
                                    <div class="col-6">
                                        <strong>Partner:</strong> {{ loan.other_party_name }}
                                    </div>
                                </div>
                                <div class="row text-sm mt-2">
                                    <div class="col-6">
                                        <strong>Start:</strong> {{ loan.start_date|date('M j, Y') }}
                                    </div>
                                    <div class="col-6">
                                        <strong>End:</strong> {{ loan.end_date|date('M j, Y') }}
                                    </div>
                                </div>
                            </div>

                            <!-- Workflow Timeline -->
                            <div class="mb-4">
                                <h6 data-help="timeline-workflow">Lending Workflow</h6>
                                
                                {% if loan.requires_digital_signature %}
                                    <div class="timeline-item {{ loan.agreement_status == 'signed' or loan.agreement_status == 'owner_bypassed' ? 'completed' : (loan.agreement_status == 'pending' ? 'current' : 'pending') }}" data-help="workflow-signature-required">
                                        <small><i class="fas fa-file-signature me-1"></i>Digital Agreement 
                                        {% if loan.agreement_status == 'owner_bypassed' %}
                                            (Owner Bypassed)
                                        {% else %}
                                            Signed
                                        {% endif %}
                                        </small>
                                    </div>
                                {% else %}
                                    <div class="timeline-item completed" data-help="workflow-no-signature">
                                        <small><i class="fas fa-handshake me-1"></i>Agreement (No Signature Required)</small>
                                    </div>
                                {% endif %}
                                
                                <div class="timeline-item {{ loan.picked_up_at ? 'completed' : (loan.status == 'active' ? 'current' : 'pending') }}">
                                    <small><i class="fas fa-hand-holding me-1"></i>Item Active/Picked Up</small>
                                    {% if loan.picked_up_at %}
                                        <br><small class="text-muted">{{ loan.picked_up_at|date('M j, g:i A') }}</small>
                                    {% endif %}
                                </div>
                                <div class="timeline-item {{ loan.return_requested_at ? 'completed' : (loan.status == 'active' ? 'current' : 'pending') }}">
                                    <small><i class="fas fa-undo me-1"></i>Return Process</small>
                                    {% if loan.return_requested_at %}
                                        <br><small class="text-muted">{{ loan.return_requested_at|date('M j, g:i A') }}</small>
                                    {% endif %}
                                </div>
                                <div class="timeline-item pending" data-help="points-system">
                                    <small><i class="fas fa-star me-1"></i>Owner Confirms & Points Awarded</small>
                                </div>
                                
                                {% if loan.owner_can_push_forward and loan.user_role == 'owner' %}
                                    <div class="mt-2" data-help="owner-push-forward">
                                        <small class="text-success">
                                            <i class="fas fa-forward me-1"></i>Owner can push forward any step
                                        </small>
                                    </div>
                                {% endif %}
                            </div>

                            <!-- Actions -->
                            <div class="d-flex gap-2 flex-wrap">
                                {% if loan.user_role == 'borrower' and loan.status == 'active' %}
                                    <button class="btn btn-warning action-btn" onclick="initiateReturn({{ loan.tracking_id }}, '{{ loan.item_name }}')">
                                        <i class="fas fa-undo me-1"></i>Start Return Process
                                    </button>
                                {% elseif loan.user_role == 'owner' and loan.status == 'return_requested' %}
                                    <button class="btn btn-success action-btn" onclick="showCompleteReturnModal({{ loan.tracking_id }}, '{{ loan.item_name }}')">
                                        <i class="fas fa-check me-1"></i>Confirm Return
                                    </button>
                                {% endif %}
                                
                                <!-- Owner Push-Forward Actions -->
                                {% if loan.user_role == 'owner' and loan.owner_can_push_forward %}
                                    {% if loan.status == 'reserved' and loan.agreement_status == 'pending' %}
                                        <button class="btn btn-info action-btn" data-help="owner-push-forward" onclick="pushForward({{ loan.tracking_id }}, 'skip_to_active', 'Skip signature requirements?')">
                                            <i class="fas fa-forward me-1"></i>Skip to Active
                                        </button>
                                    {% elseif loan.status == 'active' %}
                                        <button class="btn btn-primary action-btn" data-help="return-process" onclick="pushForward({{ loan.tracking_id }}, 'mark_returned', 'Mark item as returned?')">
                                            <i class="fas fa-check-double me-1"></i>Mark Returned
                                        </button>
                                    {% endif %}
                                {% endif %}
                                
                                <a href="/item/{{ loan.item_id }}" class="btn btn-outline-primary action-btn">
                                    <i class="fas fa-eye me-1"></i>View Item
                                </a>
                                
                                {% if loan.item_qr_code %}
                                    <a href="/qr/{{ loan.item_qr_code }}" class="btn btn-outline-secondary action-btn" data-help="qr-code-optional" target="_blank">
                                        <i class="fas fa-qrcode me-1"></i>QR Code (Optional)
                                    </a>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        {% else %}
            <div class="text-center py-5">
                <i class="fas fa-handshake fa-3x text-muted mb-3"></i>
                <h4 class="text-muted">No Active Loans</h4>
                <p class="text-muted">You don't have any items currently being lent or borrowed.</p>
                <div class="d-flex justify-content-center gap-2">
                    <a href="/browse" class="btn btn-success">
                        <i class="fas fa-search me-1"></i>Browse Items to Borrow
                    </a>
                    <a href="/create-item" class="btn btn-primary">
                        <i class="fas fa-plus me-1"></i>Add Item to Lend
                    </a>
                </div>
            </div>
        {% endif %}
    </div>

    <!-- Complete Return Modal -->
    <div class="modal fade" id="completeReturnModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-check-circle me-2"></i>Confirm Item Return
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Please confirm the return of <strong id="returnItemName"></strong>:</p>
                    <form id="completeReturnForm">
                        <input type="hidden" id="returnTrackingId">
                        <div class="mb-3">
                            <label class="form-label">Item Condition</label>
                            <select class="form-control" name="condition" required>
                                <option value="">Select condition</option>
                                <option value="excellent">Excellent - Like new</option>
                                <option value="good">Good - Normal wear</option>
                                <option value="fair">Fair - Some wear/damage</option>
                                <option value="poor">Poor - Significant damage</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes (optional)</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Any additional notes about the return..."></textarea>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-star me-2"></i>
                            <strong>Points will be awarded!</strong> Both you and the borrower will receive 1 point when you confirm this return.
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="completeReturn()">
                        <i class="fas fa-check me-1"></i>Confirm Return & Award Points
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- QR Code Modal -->
    <div class="modal fade" id="qrModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-qrcode me-2"></i>Return QR Code
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center" id="qrContent">
                    <!-- QR Code will be generated here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
    <script src="/js/contextual-help.js"></script>
    <script>
        async function initiateReturn(trackingId, itemName) {
            if (!confirm(`Start the return process for "${itemName}"?`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/loans/${trackingId}/initiate-return`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    showAlert('Return process initiated! The owner will be notified.', 'success');
                    setTimeout(() => location.reload(), 2000);
                } else {
                    throw new Error('Failed to initiate return');
                }
            } catch (error) {
                console.error('Error initiating return:', error);
                showAlert('Error starting return process. Please try again.', 'error');
            }
        }
        
        function showCompleteReturnModal(trackingId, itemName) {
            document.getElementById('returnTrackingId').value = trackingId;
            document.getElementById('returnItemName').textContent = itemName;
            new bootstrap.Modal(document.getElementById('completeReturnModal')).show();
        }
        
        async function completeReturn() {
            const trackingId = document.getElementById('returnTrackingId').value;
            const formData = new FormData(document.getElementById('completeReturnForm'));
            const data = Object.fromEntries(formData);
            
            if (!data.condition) {
                alert('Please select the item condition');
                return;
            }
            
            try {
                const response = await fetch(`/api/loans/${trackingId}/complete-return`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('completeReturnModal')).hide();
                    showAlert('Return confirmed! Points have been awarded to both parties.', 'success');
                    setTimeout(() => location.reload(), 2000);
                } else {
                    throw new Error('Failed to complete return');
                }
            } catch (error) {
                console.error('Error completing return:', error);
                showAlert('Error confirming return. Please try again.', 'error');
            }
        }
        
        async function pushForward(trackingId, action, confirmMessage) {
            if (!confirm(confirmMessage)) return;
            
            try {
                const response = await fetch(`/api/loans/${trackingId}/push-forward`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        action: action,
                        notes: 'Owner push-forward action'
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showAlert(result.message, 'success');
                    setTimeout(() => location.reload(), 2000);
                } else {
                    showAlert(result.message, 'error');
                }
            } catch (error) {
                console.error('Error pushing forward:', error);
                showAlert('Error processing action. Please try again.', 'error');
            }
        }
        
        async function showQRCode(qrCode, itemName) {
            const content = document.getElementById('qrContent');
            
            // Generate QR code
            const qrCanvas = document.createElement('canvas');
            await QRCode.toCanvas(qrCanvas, qrCode, {
                width: 200,
                margin: 2,
                color: {
                    dark: '#000000',
                    light: '#FFFFFF'
                }
            });
            
            content.innerHTML = `
                <h5 class="mb-3">Return Code for: ${itemName}</h5>
                <div class="mb-3">
                    ${qrCanvas.outerHTML}
                </div>
                <div class="text-muted">
                    <small>Scan this code when returning the item</small>
                </div>
            `;
            
            new bootstrap.Modal(document.getElementById('qrModal')).show();
        }
        
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
    </script>
</body>
</html>