<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ item.name }} - QR Status - 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>
        .qr-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .status-card {
            border-left: 5px solid #28a745;
            transition: all 0.3s ease;
        }
        
        .status-available { border-left-color: #28a745; }
        .status-reserved { border-left-color: #ffc107; }
        .status-active { border-left-color: #fd7e14; }
        .status-return-requested { border-left-color: #17a2b8; }
        
        .action-btn {
            border-radius: 25px;
            padding: 1rem 2rem;
            font-weight: bold;
            font-size: 1.1rem;
            margin: 0.5rem;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        
        .timeline-status {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .timeline-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            font-size: 1.2rem;
        }
        
        .icon-completed { background: #28a745; color: white; }
        .icon-current { background: #ffc107; color: white; animation: pulse 2s infinite; }
        .icon-pending { background: #6c757d; color: white; }
        
        @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">
    <div class="container mt-4">
        <!-- QR Header -->
        <div class="qr-container" data-help="mobile-qr-scan">
            <h1><i class="fas fa-qrcode me-2"></i>{{ item.name }}</h1>
            <p class="mb-0">QR Code: {{ qrCode }}</p>
            <small class="opacity-75">Scan this code to interact with this item</small>
        </div>

        <!-- Current Status -->
        <div class="card status-card status-{{ item.current_loan_status ?: 'available' }} mb-4">
            <div class="card-header">
                <h4 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>Current Status
                </h4>
            </div>
            <div class="card-body">
                {% if item.current_loan_status %}
                    {% if item.current_loan_status == 'reserved' %}
                        <h5 class="text-warning">
                            <i class="fas fa-clock me-2"></i>Reserved for Pickup
                        </h5>
                        <p>This item is reserved and ready for pickup by the borrower.</p>
                        <p><strong>Loan Period:</strong> {{ item.start_date|date('M j') }} - {{ item.end_date|date('M j, Y') }}</p>
                    {% elseif item.current_loan_status == 'active' %}
                        <h5 class="text-info">
                            <i class="fas fa-hand-holding me-2"></i>Currently On Loan
                        </h5>
                        <p>This item is currently being borrowed.</p>
                        <p><strong>Return Due:</strong> {{ item.end_date|date('M j, Y') }}</p>
                    {% elseif item.current_loan_status == 'return_requested' %}
                        <h5 class="text-primary">
                            <i class="fas fa-undo me-2"></i>Return in Progress
                        </h5>
                        <p>The borrower has initiated the return process.</p>
                    {% endif %}
                {% else %}
                    <h5 class="text-success">
                        <i class="fas fa-check-circle me-2"></i>Available for Lending
                    </h5>
                    <p>This item is available and can be borrowed.</p>
                    <p><strong>Owner:</strong> {{ item.owner_display_name ?: item.owner_name }}</p>
                {% endif %}
            </div>
        </div>

        <!-- Workflow Timeline -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-route me-2"></i>Lending Workflow
                </h5>
            </div>
            <div class="card-body">
                <!-- Available State -->
                <div class="timeline-status">
                    <div class="timeline-icon {{ item.current_loan_status ? 'icon-completed' : 'icon-current' }}">
                        <i class="fas fa-home"></i>
                    </div>
                    <div>
                        <h6 class="mb-1">Item Available</h6>
                        <small class="text-muted">Ready for borrowing requests</small>
                    </div>
                </div>

                {% if item.current_loan_status %}
                <!-- Reserved State -->
                <div class="timeline-status">
                    <div class="timeline-icon {{ item.current_loan_status == 'reserved' ? 'icon-current' : 'icon-completed' }}">
                        <i class="fas fa-handshake"></i>
                    </div>
                    <div>
                        <h6 class="mb-1">Agreement Signed & Reserved</h6>
                        <small class="text-muted">Digital contract completed, ready for pickup</small>
                    </div>
                </div>

                <!-- Active Loan State -->
                <div class="timeline-status">
                    <div class="timeline-icon {{ item.current_loan_status == 'active' ? 'icon-current' : (item.current_loan_status == 'return_requested' ? 'icon-completed' : 'icon-pending') }}">
                        <i class="fas fa-exchange-alt"></i>
                    </div>
                    <div>
                        <h6 class="mb-1">Item Picked Up</h6>
                        <small class="text-muted">Currently in borrower's possession</small>
                    </div>
                </div>

                <!-- Return Process -->
                <div class="timeline-status">
                    <div class="timeline-icon {{ item.current_loan_status == 'return_requested' ? 'icon-current' : 'icon-pending' }}">
                        <i class="fas fa-undo"></i>
                    </div>
                    <div>
                        <h6 class="mb-1">Return & Confirmation</h6>
                        <small class="text-muted">Item returned and owner confirms condition</small>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- Actions -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-mobile-alt me-2"></i>Quick Actions
                </h5>
            </div>
            <div class="card-body text-center">
                {% if item.current_loan_status == 'reserved' %}
                    <button class="btn btn-success action-btn" data-help="qr-code-optional" onclick="confirmAction('pickup', 'Confirm item pickup?')">
                        <i class="fas fa-hand-holding me-2"></i>Confirm Pickup
                    </button>
                {% elseif item.current_loan_status == 'active' %}
                    <button class="btn btn-warning action-btn" data-help="return-process" onclick="confirmAction('return_request', 'Initiate return process?')">
                        <i class="fas fa-undo me-2"></i>Initiate Return
                    </button>
                {% elseif item.current_loan_status == 'return_requested' %}
                    <button class="btn btn-primary action-btn" data-help="return-process" onclick="showReturnModal()">
                        <i class="fas fa-check me-2"></i>Confirm Return
                    </button>
                {% else %}
                    <a href="/item/{{ item.id }}" class="btn btn-primary action-btn">
                        <i class="fas fa-eye me-2"></i>View Item Details
                    </a>
                    <a href="/browse" class="btn btn-success action-btn">
                        <i class="fas fa-search me-2"></i>Browse More Items
                    </a>
                    <a href="/help" class="btn btn-info action-btn" data-help="qr-code-optional">
                        <i class="fas fa-question-circle me-2"></i>Help Guide
                    </a>
                {% endif %}
            </div>
        </div>

        <!-- Item Details -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-tag me-2"></i>Item Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        {% if item.primary_logo %}
                            <img src="/lendable_items/{{ item.primary_logo }}" class="img-fluid rounded" alt="{{ item.name }}">
                        {% else %}
                            <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 200px;">
                                <i class="fas fa-image fa-3x text-muted"></i>
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-8">
                        <h4>{{ item.name }}</h4>
                        <p class="text-muted">{{ item.description }}</p>
                        <div class="row">
                            <div class="col-sm-6">
                                <strong>Owner:</strong> {{ item.owner_display_name ?: item.owner_name }}<br>
                                <strong>Item ID:</strong> #{{ item.id }}
                            </div>
                            <div class="col-sm-6">
                                <strong>QR Code:</strong> {{ qrCode }}<br>
                                <strong>Status:</strong> 
                                <span class="badge bg-{{ item.current_loan_status == 'active' ? 'warning' : 'success' }}">
                                    {{ item.current_loan_status ?: 'Available' }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Return Confirmation Modal -->
    <div class="modal fade" id="returnModal" 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">
                    <form id="returnForm">
                        <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..."></textarea>
                        </div>
                        <div class="alert alert-success">
                            <i class="fas fa-star me-2"></i>
                            <strong>Points will be awarded!</strong> Both owner and borrower will receive 1 point.
                        </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="confirmReturn()">
                        <i class="fas fa-check me-1"></i>Complete Return
                    </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/sweetalert2@11"></script>
    <script src="/js/contextual-help.js"></script>
    <script>
        async function confirmAction(action, message) {
            if (!confirm(message)) return;
            
            try {
                const response = await fetch(`/api/qr/{{ qrCode }}/action`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 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:', error);
                showAlert('Error processing action. Please try again.', 'error');
            }
        }
        
        function showReturnModal() {
            new bootstrap.Modal(document.getElementById('returnModal')).show();
        }
        
        async function confirmReturn() {
            const formData = new FormData(document.getElementById('returnForm'));
            const data = Object.fromEntries(formData);
            
            if (!data.condition) {
                alert('Please select item condition');
                return;
            }
            
            try {
                const response = await fetch(`/api/qr/{{ qrCode }}/action`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        action: 'return_complete',
                        notes: `Condition: ${data.condition}. ${data.notes || ''}`
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    bootstrap.Modal.getInstance(document.getElementById('returnModal')).hide();
                    showAlert(result.message, 'success');
                    setTimeout(() => location.reload(), 2000);
                } else {
                    showAlert(result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showAlert('Error completing return. Please try again.', 'error');
            }
        }
        
        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>