<style>
    .client-photo-popup {
        position: absolute;
        z-index: 1000;
        background: white;
        border-radius: 8px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        padding: 16px;
        min-width: 280px;
        pointer-events: none;
        opacity: 0;
        transition: opacity 0.2s ease-in-out;
        border: 1px solid #e5e7eb;
    }
    
    .client-photo-popup.show {
        opacity: 1;
    }
    
    .client-photo-popup img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        object-fit: cover;
        border: 3px solid #3C9EBD;
        margin-bottom: 12px;
    }
    
    .client-photo-popup .popup-content {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
    
    .client-photo-popup .popup-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 13px;
        padding: 4px 0;
        border-bottom: 1px solid #f3f4f6;
    }
    
    .client-photo-popup .popup-row:last-child {
        border-bottom: none;
    }
    
    .client-photo-popup .popup-label {
        color: #6b7280;
        font-weight: 500;
    }
    
    .client-photo-popup .popup-value {
        color: #111827;
        font-weight: 600;
        text-align: right;
    }
    
    .client-photo-popup .popup-header {
        font-size: 14px;
        font-weight: 700;
        color: #111827;
        margin-bottom: 8px;
        text-align: center;
    }
    
    .client-photo-container {
        position: relative;
        display: inline-block;
    }
</style>

<table class="min-w-full divide-y divide-gray-300">
    <thead class="bg-gray-50">
        <tr>
            <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">
                Photo
            </th>
            <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">
                Loan Details
            </th>
            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                Client Information
            </th>
            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                Status
            </th>
            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                Amount
            </th>
            <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                <span class="sr-only">Actions</span>
            </th>
        </tr>
    </thead>
    <tbody class="divide-y divide-gray-200 bg-white">
        {% for application in loans %}
        <tr>
            <td class="whitespace-nowrap py-4 pl-4 pr-3 sm:pl-6">
                <div class="client-photo-container" 
                     data-client-name="{{ application.borrower.get_full_name }}"
                     data-client-phone="{{ application.borrower.phone_number }}"
                     data-loan-number="{% if application.loan %}{{ application.loan.loan_number }}{% else %}{{ application.application_number }}{% endif %}"
                     data-loan-amount="{% if application.loan %}{{ application.loan.principal_amount|floatformat:2 }}{% else %}{{ application.requested_amount|floatformat:2 }}{% endif %}"
                     data-loan-status="{% if application.loan %}{{ application.loan.get_status_display }}{% else %}{{ application.get_status_display }}{% endif %}"
                     data-loan-due-date="{% if application.loan %}{{ application.loan.due_date|date:'Y-m-d' }}{% else %}N/A{% endif %}"
                     data-outstanding="{% if application.loan %}{{ application.loan.outstanding_amount|floatformat:2 }}{% else %}N/A{% endif %}"
                     data-days-overdue="{% if application.loan.is_overdue %}{{ application.loan.days_overdue }}{% else %}0{% endif %}">
                    {% if application.borrower.selfie %}
                    <img src="{{ application.borrower.selfie.url }}" 
                         alt="{{ application.borrower.get_full_name }}"
                         class="h-12 w-12 rounded-full object-cover border-2 border-gray-200 cursor-pointer hover:border-primary transition-all">
                    {% else %}
                    <div class="h-12 w-12 rounded-full bg-primary flex items-center justify-center cursor-pointer hover:bg-primary-dark transition-all">
                        <span class="text-sm font-medium text-white">
                            {{ application.borrower.first_name|first }}{{ application.borrower.last_name|first }}
                        </span>
                    </div>
                    {% endif %}
                </div>
            </td>
            <td class="whitespace-nowrap py-4 pl-4 pr-3 sm:pl-6">
                <div class="flex flex-col">
                    <div class="font-medium text-gray-900">
                        {% if application.loan %}
                            {{ application.loan.loan_number }} - {{ application.loan_product.get_product_type_display }}
                        {% else %}
                            {{ application.application_number }} - {{ application.loan_product.get_product_type_display }}
                        {% endif %}
                    </div>
                    <div class="text-gray-500">
                        Duration: {{ application.requested_duration }} days
                    </div>
                    <div class="flex items-center gap-2 text-gray-500">
                        <span>📅</span>
                        {% if application.loan %}
                            Disbursed: {{ application.loan.disbursement_date|date:"Y-m-d" }}
                        {% else %}
                            Applied: {{ application.submitted_at|date:"Y-m-d" }}
                        {% endif %}
                    </div>
                </div>
            </td>
            <td class="whitespace-nowrap px-3 py-4">
                <div class="flex flex-col">
                    <div class="font-medium text-gray-900">{{ application.borrower.get_full_name }}</div>
                    <div class="text-gray-500">{{ application.borrower.phone_number }}</div>
                    <div class="text-gray-500">{{ application.borrower.email }}</div>
                </div>
            </td>
            <td class="whitespace-nowrap px-3 py-4">
                {% if application.loan %}
                    <div class="flex flex-col gap-1">
                        <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 
                            {% if application.loan.status == 'active' %}
                                {% if application.loan.is_overdue %}bg-red-100 text-red-800{% else %}bg-green-100 text-green-800{% endif %}
                            {% elif application.loan.status == 'paid' %}bg-blue-100 text-blue-800
                            {% elif application.loan.status == 'defaulted' %}bg-red-100 text-red-800
                            {% elif application.loan.status == 'written_off' %}bg-gray-100 text-gray-800
                            {% elif application.loan.status == 'rolled_over' %}bg-purple-100 text-purple-800
                            {% endif %}">
                            {{ application.loan.get_status_display }}
                        </span>
                        {% if application.loan.is_overdue %}
                        <span class="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-1 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-600/20">
                            <span>⚠️</span>
                            <span>{{ application.loan.days_overdue }} days overdue</span>
                        </span>
                        {% endif %}
                    </div>
                {% else %}
                    <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 
                        {% if application.status == 'pending' %}bg-yellow-100 text-yellow-800
                        {% elif application.status == 'under_review' %}bg-blue-100 text-blue-800
                        {% elif application.status == 'approved' %}bg-green-100 text-green-800
                        {% elif application.status == 'rejected' %}bg-red-100 text-red-800
                        {% else %}bg-gray-100 text-gray-800{% endif %}">
                        {{ application.get_status_display }}
                    </span>
                {% endif %}
            </td>
            <td class="whitespace-nowrap px-3 py-4">
                <div class="flex flex-col">
                    <div class="font-medium text-gray-900">
                        {% if application.loan %}
                            KES {{ application.loan.principal_amount|floatformat:2 }}
                        {% else %}
                            KES {{ application.requested_amount|floatformat:2 }}
                        {% endif %}
                    </div>
                    <div class="text-gray-500">
                        {% if application.loan %}
                            Interest: KES {{ application.loan.interest_amount|floatformat:2 }}
                        {% else %}
                            Interest: KES {{ application.interest_amount|floatformat:2 }}
                        {% endif %}
                    </div>
                    <div class="text-gray-500">
                        {% if application.loan %}
                            Total: KES {{ application.loan.total_amount|floatformat:2 }}
                        {% else %}
                            Total: KES {{ application.total_amount|floatformat:2 }}
                        {% endif %}
                    </div>
                </div>
            </td>
            <td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                <div class="flex justify-end space-x-2">
                    {% if application.loan %}
                        <!-- View Details -->
                        <a href="{% url 'loans:loan_detail' pk=application.loan.pk %}" 
                           class="text-gray-600 hover:text-gray-900 transition-colors duration-150"
                           title="View Details">
                            <i class="fas fa-eye"></i>
                        </a>
                        
                        <!-- Amortization Schedule -->
                        <a href="{% url 'loans:loan_amortization' pk=application.loan.pk %}" 
                           class="text-purple-600 hover:text-purple-800 transition-colors duration-150"
                           title="Amortization Schedule">
                            <span>🧮</span>
                        </a>
                        
                        {% if application.loan.status == 'active' %}
                        <!-- Record Payment -->
                        <button onclick="showRepaymentModal('{{ application.loan.pk }}')"
                                class="text-green-600 hover:text-green-800 transition-colors duration-150"
                                title="Record Payment">
                            <span>💵</span>
                        </button>
                        
                        <!-- Request Rollover -->
                        <button onclick="showRolloverModal('{{ application.loan.pk }}')"
                                class="text-blue-600 hover:text-blue-800 transition-colors duration-150"
                                title="Request Rollover">
                            <span>↷</span>
                        </button>
                        {% endif %}
                        
                        {% if user.is_admin %}
                        <!-- Edit Loan (Admin Only) -->
                        <a href="{% url 'loans:edit_loan' pk=application.loan.pk %}"
                           class="text-blue-600 hover:text-blue-800 transition-colors duration-150"
                           title="Edit Loan">
                            <span>✏️</span>
                        </a>
                        
                        <!-- Delete Loan (Admin Only) -->
                        <a href="{% url 'loans:delete_loan' pk=application.loan.pk %}"
                           class="text-red-600 hover:text-red-800 transition-colors duration-150"
                           title="Delete Loan">
                            <span>🗑️</span>
                        </a>
                        
                        <!-- Update Status (Admin Only) -->
                        <button onclick="showStatusUpdateModal('{{ application.loan.pk }}', '{{ application.loan.status }}', '{{ application.loan.loan_number }}')"
                                class="text-purple-600 hover:text-purple-800 transition-colors duration-150"
                                title="Update Status">
                            <span>⚙️</span>
                        </button>
                        {% endif %}
                    {% else %}
                        {% if application.status == 'pending' %}
                        <!-- Approve Application -->
                        <a href="{% url 'loans:approve_application' pk=application.pk %}"
                           class="text-green-600 hover:text-green-800 transition-colors duration-150"
                           title="Approve Application">
                            <span>✓</span>
                        </a>
                        
                        <!-- Reject Application -->
                        <a href="{% url 'loans:reject_application' pk=application.pk %}"
                           class="text-red-600 hover:text-red-800 transition-colors duration-150"
                           title="Reject Application">
                            <span>✕</span>
                        </a>
                        {% endif %}
                    {% endif %}
                </div>
            </td>
        </tr>
        {% empty %}
        <tr>
            <td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">
                <div class="flex flex-col items-center py-8">
                    <span>💵</span>
                    <p>No loans found matching your criteria.</p>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Create popup element
    const popup = document.createElement('div');
    popup.className = 'client-photo-popup';
    popup.innerHTML = `
        <div class="text-center">
            <img src="" alt="Client Photo" id="popupPhoto" style="display: none;">
            <div id="popupInitials" class="h-20 w-20 rounded-full bg-primary flex items-center justify-center mx-auto mb-3" style="display: none;">
                <span class="text-2xl font-bold text-white"></span>
            </div>
        </div>
        <div class="popup-header" id="popupName"></div>
        <div class="popup-content">
            <div class="popup-row">
                <span class="popup-label">📞 Phone:</span>
                <span class="popup-value" id="popupPhone"></span>
            </div>
            <div class="popup-row">
                <span class="popup-label">🔢 Loan #:</span>
                <span class="popup-value" id="popupLoanNumber"></span>
            </div>
            <div class="popup-row">
                <span class="popup-label">💰 Amount:</span>
                <span class="popup-value" id="popupAmount"></span>
            </div>
            <div class="popup-row">
                <span class="popup-label">📊 Status:</span>
                <span class="popup-value" id="popupStatus"></span>
            </div>
            <div class="popup-row">
                <span class="popup-label">📅 Due Date:</span>
                <span class="popup-value" id="popupDueDate"></span>
            </div>
            <div class="popup-row" id="outstandingRow">
                <span class="popup-label">💳 Outstanding:</span>
                <span class="popup-value" id="popupOutstanding"></span>
            </div>
            <div class="popup-row" id="overdueRow" style="display: none;">
                <span class="popup-label">⚠️ Days Overdue:</span>
                <span class="popup-value" id="popupDaysOverdue" style="color: #dc2626;"></span>
            </div>
        </div>
    `;
    document.body.appendChild(popup);
    
    // Get all client photo containers
    const photoContainers = document.querySelectorAll('.client-photo-container');
    
    let hideTimeout;
    
    photoContainers.forEach(container => {
        const img = container.querySelector('img, div');
        
        img.addEventListener('mouseenter', function(e) {
            clearTimeout(hideTimeout);
            
            // Get data from container
            const clientName = container.dataset.clientName;
            const clientPhone = container.dataset.clientPhone;
            const loanNumber = container.dataset.loanNumber;
            const loanAmount = container.dataset.loanAmount;
            const loanStatus = container.dataset.loanStatus;
            const dueDate = container.dataset.loanDueDate;
            const outstanding = container.dataset.outstanding;
            const daysOverdue = parseInt(container.dataset.daysOverdue || '0');
            
            // Update popup content
            document.getElementById('popupName').textContent = clientName;
            document.getElementById('popupPhone').textContent = clientPhone;
            document.getElementById('popupLoanNumber').textContent = loanNumber;
            document.getElementById('popupAmount').textContent = 'KES ' + loanAmount;
            document.getElementById('popupStatus').textContent = loanStatus;
            document.getElementById('popupDueDate').textContent = dueDate;
            
            // Handle outstanding amount
            if (outstanding !== 'N/A') {
                document.getElementById('popupOutstanding').textContent = 'KES ' + outstanding;
                document.getElementById('outstandingRow').style.display = 'flex';
            } else {
                document.getElementById('outstandingRow').style.display = 'none';
            }
            
            // Handle overdue days
            if (daysOverdue > 0) {
                document.getElementById('popupDaysOverdue').textContent = daysOverdue + ' days';
                document.getElementById('overdueRow').style.display = 'flex';
            } else {
                document.getElementById('overdueRow').style.display = 'none';
            }
            
            // Handle photo or initials
            const popupPhoto = document.getElementById('popupPhoto');
            const popupInitials = document.getElementById('popupInitials');
            
            if (img.tagName === 'IMG') {
                popupPhoto.src = img.src;
                popupPhoto.style.display = 'block';
                popupInitials.style.display = 'none';
            } else {
                const initials = img.querySelector('span').textContent;
                popupInitials.querySelector('span').textContent = initials;
                popupInitials.style.display = 'flex';
                popupPhoto.style.display = 'none';
            }
            
            // Position popup
            const rect = container.getBoundingClientRect();
            const popupRect = popup.getBoundingClientRect();
            
            // Calculate position (to the right of the photo)
            let left = rect.right + 10;
            let top = rect.top + (rect.height / 2) - (popupRect.height / 2);
            
            // Adjust if popup goes off screen
            if (left + popupRect.width > window.innerWidth) {
                left = rect.left - popupRect.width - 10; // Show on left instead
            }
            
            if (top < 10) {
                top = 10;
            } else if (top + popupRect.height > window.innerHeight - 10) {
                top = window.innerHeight - popupRect.height - 10;
            }
            
            popup.style.left = left + 'px';
            popup.style.top = top + window.scrollY + 'px';
            popup.classList.add('show');
        });
        
        img.addEventListener('mouseleave', function() {
            hideTimeout = setTimeout(() => {
                popup.classList.remove('show');
            }, 200);
        });
    });
    
    // Keep popup visible when hovering over it
    popup.addEventListener('mouseenter', function() {
        clearTimeout(hideTimeout);
    });
    
    popup.addEventListener('mouseleave', function() {
        popup.classList.remove('show');
    });
});
</script>