{% extends 'base.html' %}
{% load static %}
{% load humanize %}

{% block title %}Enhanced Portfolio Assignment Center{% endblock %}

{% block extra_head %}
<link href="https://cdn.tailwindcss.com/3.4.17" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<style>
    .client-card {
        @apply border-2 border-gray-200 rounded-xl p-4 mb-3 cursor-pointer transition-all duration-300 hover:border-blue-500 hover:shadow-lg hover:-translate-y-1;
    }
    
    .client-card.selected {
        @apply border-blue-500 bg-gradient-to-r from-blue-50 to-blue-100 transform translate-x-2 shadow-lg;
    }
    
    .manager-card {
        @apply border-2 border-gray-200 rounded-xl p-5 mb-4 cursor-pointer transition-all duration-300 hover:border-green-500 hover:shadow-lg hover:-translate-y-1;
    }
    
    .manager-card.selected {
        @apply border-green-500 bg-gradient-to-r from-green-50 to-green-100 transform -translate-y-2 shadow-xl;
    }
    
    .capacity-bar {
        @apply w-full bg-gray-200 rounded-full h-3 overflow-hidden;
    }
    
    .capacity-fill {
        @apply h-full transition-all duration-500 rounded-full;
    }
    
    .capacity-low { @apply bg-gradient-to-r from-green-400 to-green-500; }
    .capacity-medium { @apply bg-gradient-to-r from-yellow-400 to-yellow-500; }
    .capacity-high { @apply bg-gradient-to-r from-orange-400 to-orange-500; }
    .capacity-full { @apply bg-gradient-to-r from-red-400 to-red-500; }
    
    .assignment-mode {
        @apply p-4 border-2 border-gray-200 rounded-xl cursor-pointer transition-all duration-300 hover:border-blue-500 hover:shadow-md;
    }
    
    .assignment-mode.active {
        @apply border-blue-500 bg-blue-50 shadow-lg;
    }
    
    .stats-card {
        @apply bg-white rounded-xl shadow-lg p-6 border-l-4 transition-all duration-300 hover:shadow-xl hover:-translate-y-1;
    }
    
    .animate-pulse-slow {
        animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
    }
</style>
{% endblock %}

{% block content %}
<div class="bg-gradient-to-br from-gray-50 via-white to-blue-50 min-h-screen py-8">
    <div class="container mx-auto px-4 max-w-7xl">
        
        <!-- Enhanced Header with Real-time Stats -->
        <div class="bg-gradient-to-r from-blue-600 via-purple-600 to-blue-800 rounded-2xl shadow-2xl p-8 mb-8 text-white">
            <div class="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
                <div>
                    <h1 class="text-4xl font-bold mb-2 flex items-center gap-3">
                        <div class="p-3 bg-white/20 rounded-xl backdrop-blur-sm">
                            <i class="fas fa-users-cog text-3xl"></i>
                        </div>
                        Portfolio Assignment Center
                    </h1>
                    <p class="text-blue-100 text-lg">Intelligent client-manager assignment with advanced analytics</p>
                    <div class="flex flex-wrap gap-3 mt-4">
                        <span class="px-4 py-2 bg-white/20 rounded-full text-sm font-medium backdrop-blur-sm">
                            <span>⏰</span>Real-time capacity monitoring
                        </span>
                        <span class="px-4 py-2 bg-white/20 rounded-full text-sm font-medium backdrop-blur-sm">
                            <span>📈</span>Performance-based assignment
                        </span>
                    </div>
                </div>
                
                <!-- Quick Stats -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 text-center">
                    <div class="bg-white/20 rounded-xl p-4 backdrop-blur-sm">
                        <div class="text-2xl font-bold">{{ assignment_stats.total_unassigned }}</div>
                        <div class="text-sm text-blue-100">Unassigned</div>
                    </div>
                    <div class="bg-white/20 rounded-xl p-4 backdrop-blur-sm">
                        <div class="text-2xl font-bold">{{ assignment_stats.total_managers }}</div>
                        <div class="text-sm text-blue-100">Managers</div>
                    </div>
                    <div class="bg-white/20 rounded-xl p-4 backdrop-blur-sm">
                        <div class="text-2xl font-bold">{{ assignment_stats.avg_clients_per_manager|floatformat:0 }}</div>
                        <div class="text-sm text-blue-100">Avg/Manager</div>
                    </div>
                    <div class="bg-white/20 rounded-xl p-4 backdrop-blur-sm">
                        <div class="text-2xl font-bold animate-pulse-slow">{{ recent_assignments|length }}</div>
                        <div class="text-sm text-blue-100">Recent</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Assignment Mode Selection -->
        <div class="bg-white rounded-2xl shadow-xl p-6 mb-8">
            <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-3">
                <span>⚙️</span>
                Assignment Mode
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Manual Assignment -->
                <div class="assignment-mode active" id="manual-mode" onclick="setAssignmentMode('manual')">
                    <div class="flex items-center gap-4">
                        <div class="p-3 bg-blue-100 rounded-xl">
                            <i class="fas fa-hand-pointer text-blue-600 text-xl"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold text-gray-800">Manual Assignment</h3>
                            <p class="text-gray-600">Select specific clients and managers for precise control</p>
                        </div>
                    </div>
                </div>
                
                <!-- Auto Assignment -->
                <div class="assignment-mode" id="auto-mode" onclick="setAssignmentMode('auto')">
                    <div class="flex items-center gap-4">
                        <div class="p-3 bg-green-100 rounded-xl">
                            <i class="fas fa-magic text-green-600 text-xl"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold text-gray-800">Automatic Assignment</h3>
                            <p class="text-gray-600">AI-powered bulk assignment using smart algorithms</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 xl:grid-cols-4 gap-8">
            
            <!-- Clients Section (Manual Mode) -->
            <div class="xl:col-span-2" id="clients-section">
                <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-50 to-blue-100 p-6 border-b border-blue-200">
                        <div class="flex justify-between items-center">
                            <h2 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                                <span>👥</span>
                                Available Clients
                                <span class="bg-blue-500 text-white px-3 py-1 rounded-full text-sm">{{ assignment_stats.total_unassigned }}</span>
                            </h2>
                            <div class="flex items-center gap-3">
                                <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">
                                    <span id="selected-count">0</span> selected
                                </span>
                                <button onclick="selectAllClients()" class="px-3 py-1 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600 transition-all">
                                    Select All
                                </button>
                            </div>
                        </div>
                        
                        <!-- Client Search -->
                        <div class="mt-4">
                            <div class="relative">
                                <input type="text" id="client-search" placeholder="Search clients by name, phone, or location..." 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <span>🔍</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="p-4 max-h-[600px] overflow-y-auto" id="clients-container">
                        {% for client in unassigned_clients %}
                        <div class="client-card" data-client-id="{{ client.id }}" 
                             data-search-text="{{ client.get_full_name|lower }} {{ client.phone_number }} {{ client.location|default:''|lower }}">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4">
                                    <div class="flex-shrink-0 w-12 h-12 bg-gradient-to-br from-blue-500 to-blue-700 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                        {{ client.get_initials }}
                                    </div>
                                    <div>
                                        <h3 class="text-gray-900 font-semibold text-lg">{{ client.get_full_name }}</h3>
                                        <div class="flex items-center gap-4 text-sm text-gray-600">
                                            <span><span>📞</span>{{ client.phone_number }}</span>
                                            {% if client.location %}
                                            <span><span>📍</span>{{ client.location }}</span>
                                            {% endif %}
                                        </div>
                                        <div class="flex items-center gap-2 mt-1">
                                            <span class="bg-gray-100 text-gray-700 px-2 py-1 rounded-full text-xs">{{ client.business_type|default:"General" }}</span>
                                            {% if client.branch %}
                                            <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded-full text-xs">{{ client.branch.name }}</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                <div class="selection-indicator opacity-0 scale-0 transition-all duration-200">
                                    <div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white">
                                        <span>✓</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="text-center py-12">
                            <span>👥</span>
                            <h3 class="text-xl font-semibold text-gray-600 mb-2">No Unassigned Clients</h3>
                            <p class="text-gray-500">All clients have been assigned to portfolio managers.</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>

            <!-- Auto Assignment Section (Hidden by default) -->
            <div class="xl:col-span-2 hidden" id="auto-section">
                <div class="bg-white rounded-2xl shadow-xl p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
                        <i class="fas fa-magic text-green-600"></i>
                        Automatic Assignment Configuration
                    </h2>
                    
                    <div class="space-y-6">
                        <!-- Strategy Selection -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-3">Assignment Strategy</label>
                            <div class="grid grid-cols-1 gap-3">
                                <label class="flex items-center p-4 border-2 border-gray-200 rounded-xl cursor-pointer hover:border-blue-500 transition-all">
                                    <input type="radio" name="auto_strategy" value="round_robin" checked class="mr-3">
                                    <div>
                                        <div class="font-semibold">Round Robin</div>
                                        <div class="text-sm text-gray-600">Distribute clients evenly across all managers</div>
                                    </div>
                                </label>
                                
                                <label class="flex items-center p-4 border-2 border-gray-200 rounded-xl cursor-pointer hover:border-blue-500 transition-all">
                                    <input type="radio" name="auto_strategy" value="least_loaded" class="mr-3">
                                    <div>
                                        <div class="font-semibold">Least Loaded</div>
                                        <div class="text-sm text-gray-600">Assign to managers with fewest clients first</div>
                                    </div>
                                </label>
                                
                                <label class="flex items-center p-4 border-2 border-gray-200 rounded-xl cursor-pointer hover:border-blue-500 transition-all">
                                    <input type="radio" name="auto_strategy" value="geographic" class="mr-3">
                                    <div>
                                        <div class="font-semibold">Geographic</div>
                                        <div class="text-sm text-gray-600">Match clients with managers in same branch/area</div>
                                    </div>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Assignment Limits -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Maximum Assignments</label>
                            <input type="number" name="max_assignments" value="50" min="1" max="500" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <p class="text-sm text-gray-600 mt-1">Limit the number of clients to assign in this batch</p>
                        </div>
                        
                        <!-- Preview -->
                        <div class="bg-blue-50 border border-blue-200 rounded-xl p-4">
                            <h4 class="font-semibold text-blue-800 mb-2">Assignment Preview</h4>
                            <div class="text-sm text-blue-700">
                                <div>Available clients: <span class="font-semibold">{{ assignment_stats.total_unassigned }}</span></div>
                                <div>Available managers: <span class="font-semibold">{{ assignment_stats.total_managers }}</span></div>
                                <div>Estimated assignments per manager: <span class="font-semibold" id="estimated-per-manager">~{{ assignment_stats.total_unassigned|div:assignment_stats.total_managers|floatformat:0 }}</span></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Portfolio Managers Section -->
            <div class="xl:col-span-2">
                <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-green-50 to-green-100 p-6 border-b border-green-200">
                        <h2 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                            <span>👔</span>
                            Portfolio Managers
                            <span class="bg-green-500 text-white px-3 py-1 rounded-full text-sm">{{ assignment_stats.total_managers }}</span>
                        </h2>
                        <p class="text-gray-600 mt-1">Select a manager to assign clients (Manual mode only)</p>
                    </div>
                    
                    <div class="p-4 max-h-[600px] overflow-y-auto">
                        {% for manager in portfolio_managers %}
                        <div class="manager-card" data-manager-id="{{ manager.id }}">
                            <div class="flex items-center justify-between mb-4">
                                <div class="flex items-center gap-4">
                                    <div class="flex-shrink-0 w-14 h-14 bg-gradient-to-br from-green-500 to-green-700 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                        {{ manager.get_initials }}
                                    </div>
                                    <div>
                                        <h3 class="text-gray-900 font-semibold text-lg">{{ manager.get_full_name }}</h3>
                                        <div class="flex items-center gap-3 text-sm text-gray-600">
                                            <span class="bg-gray-100 px-2 py-1 rounded-full">{{ manager.role|title }}</span>
                                            {% if manager.branch %}
                                            <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded-full">{{ manager.branch.name }}</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-gray-800">{{ manager.client_count }}</div>
                                    <div class="text-sm text-gray-600">clients</div>
                                </div>
                            </div>
                            
                            <!-- Capacity Bar -->
                            <div class="mb-3">
                                <div class="flex justify-between text-sm text-gray-600 mb-1">
                                    <span>Capacity</span>
                                    <span>{{ manager.client_count }}/{{ manager.max_capacity }}</span>
                                </div>
                                <div class="capacity-bar">
                                    <div class="capacity-fill {% if manager.capacity_percentage < 50 %}capacity-low{% elif manager.capacity_percentage < 75 %}capacity-medium{% elif manager.capacity_percentage < 90 %}capacity-high{% else %}capacity-full{% endif %}" 
                                         style="width: {{ manager.capacity_percentage }}%"></div>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    {{ manager.available_slots }} slots available
                                </div>
                            </div>
                            
                            <!-- Performance Metrics -->
                            <div class="grid grid-cols-2 gap-3 text-sm">
                                <div class="bg-blue-50 p-2 rounded-lg">
                                    <div class="text-blue-600 font-semibold">{{ manager.active_loans }}</div>
                                    <div class="text-blue-500 text-xs">Active Loans</div>
                                </div>
                                <div class="bg-green-50 p-2 rounded-lg">
                                    <div class="text-green-600 font-semibold">KES {{ manager.total_portfolio_value|floatformat:0|intcomma }}</div>
                                    <div class="text-green-500 text-xs">Portfolio Value</div>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="text-center py-12">
                            <span>👔</span>
                            <h3 class="text-xl font-semibold text-gray-600 mb-2">No Portfolio Managers</h3>
                            <p class="text-gray-500">No active portfolio managers found.</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- Assignment Summary & Actions -->
        <div class="mt-8 grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- Assignment Summary -->
            <div class="bg-gradient-to-r from-blue-50 to-blue-100 border-2 border-blue-300 rounded-xl p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                    <i class="fas fa-clipboard-list text-blue-600"></i>
                    Assignment Summary
                </h3>
                <div class="space-y-3">
                    <div class="flex justify-between">
                        <span class="text-gray-600">Selected Clients:</span>
                        <span class="font-semibold" id="summary-clients">0</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Target Manager:</span>
                        <span class="font-semibold" id="summary-manager">None selected</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Assignment Mode:</span>
                        <span class="font-semibold" id="summary-mode">Manual</span>
                    </div>
                </div>
            </div>
            
            <!-- Assignment Reason -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                    <i class="fas fa-comment-alt text-purple-600"></i>
                    Assignment Reason
                </h3>
                <textarea id="assignment-reason" name="reason" 
                    class="w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all" 
                    rows="4" placeholder="Enter reason for assignment (optional)..."></textarea>
            </div>
            
            <!-- Action Buttons -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                    <span>⚡</span>
                    Actions
                </h3>
                <div class="space-y-3">
                    <button id="assign-button" onclick="executeAssignment()" disabled
                        class="w-full bg-gradient-to-r from-blue-500 to-blue-700 text-white font-semibold py-4 px-6 rounded-xl shadow-lg transition-all duration-200 hover:-translate-y-1 hover:shadow-xl disabled:opacity-50 disabled:bg-gray-400 disabled:hover:translate-y-0 disabled:hover:shadow-none">
                        <span>👤+</span>
                        <span id="assign-button-text">Assign Clients</span>
                    </button>
                    
                    <button onclick="resetAssignment()" 
                        class="w-full bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-3 px-6 rounded-xl transition-all">
                        <span>↶</span>
                        Reset Selection
                    </button>
                    
                    <a href="{% url 'users:portfolio_dashboard' %}" 
                        class="w-full bg-green-100 hover:bg-green-200 text-green-700 font-semibold py-3 px-6 rounded-xl transition-all text-center block">
                        <span>📈</span>
                        View Dashboard
                    </a>
                </div>
            </div>
        </div>

        <!-- Recent Assignments -->
        {% if recent_assignments %}
        <div class="mt-8 bg-white rounded-2xl shadow-xl p-6">
            <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
                <i class="fas fa-history text-indigo-600"></i>
                Recent Assignments (Last 30 Days)
            </h3>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Client</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Manager</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Assigned By</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Reason</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for assignment in recent_assignments %}
                        <tr class="hover:bg-gray-50 transition-colors">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-8 w-8 bg-blue-500 rounded-full flex items-center justify-center text-white text-sm font-bold">
                                        {{ assignment.client.get_initials }}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">{{ assignment.client.get_full_name }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-8 w-8 bg-green-500 rounded-full flex items-center justify-center text-white text-sm font-bold">
                                        {{ assignment.portfolio_manager.get_initials }}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">{{ assignment.portfolio_manager.get_full_name }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ assignment.assigned_by.get_full_name }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                {{ assignment.assigned_date|date:"M d, Y H:i" }}
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500">
                                {{ assignment.reason|truncatechars:50 }}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Hidden Forms -->
<form id="manual-assignment-form" method="post" action="{% url 'users:assign_clients' %}" class="hidden">
    {% csrf_token %}
    <input type="hidden" name="assignment_type" value="manual">
    <input type="hidden" name="client_ids" id="client_ids">
    <input type="hidden" name="manager_id" id="manager_id">
    <input type="hidden" name="reason" id="reason">
</form>

<form id="auto-assignment-form" method="post" action="{% url 'users:assign_clients' %}" class="hidden">
    {% csrf_token %}
    <input type="hidden" name="assignment_type" value="bulk_auto">
    <input type="hidden" name="auto_strategy" id="auto_strategy">
    <input type="hidden" name="max_assignments" id="max_assignments">
    <input type="hidden" name="reason" id="auto_reason">
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Global variables
    let selectedClients = [];
    let selectedManager = null;
    let assignmentMode = 'manual';
    
    // DOM elements
    const clientCards = document.querySelectorAll('.client-card');
    const managerCards = document.querySelectorAll('.manager-card');
    const selectedCountEl = document.getElementById('selected-count');
    const summaryClientsEl = document.getElementById('summary-clients');
    const summaryManagerEl = document.getElementById('summary-manager');
    const summaryModeEl = document.getElementById('summary-mode');
    const assignButton = document.getElementById('assign-button');
    const assignButtonText = document.getElementById('assign-button-text');
    const clientSearch = document.getElementById('client-search');
    
    // Initialize event listeners
    initializeEventListeners();
    
    function initializeEventListeners() {
        // Client selection
        clientCards.forEach(card => {
            card.addEventListener('click', function() {
                if (assignmentMode === 'manual') {
                    toggleClientSelection(this);
                }
            });
        });
        
        // Manager selection
        managerCards.forEach(card => {
            card.addEventListener('click', function() {
                if (assignmentMode === 'manual') {
                    toggleManagerSelection(this);
                }
            });
        });
        
        // Client search
        if (clientSearch) {
            clientSearch.addEventListener('input', function() {
                filterClients(this.value);
            });
        }
        
        // Auto strategy change
        const strategyRadios = document.querySelectorAll('input[name="auto_strategy"]');
        strategyRadios.forEach(radio => {
            radio.addEventListener('change', updateAutoPreview);
        });
        
        // Max assignments change
        const maxAssignmentsInput = document.querySelector('input[name="max_assignments"]');
        if (maxAssignmentsInput) {
            maxAssignmentsInput.addEventListener('input', updateAutoPreview);
        }
    }
    
    function toggleClientSelection(card) {
        const clientId = card.dataset.clientId;
        const indicator = card.querySelector('.selection-indicator');
        
        if (selectedClients.includes(clientId)) {
            // Deselect
            selectedClients = selectedClients.filter(id => id !== clientId);
            card.classList.remove('selected');
            indicator.classList.remove('opacity-100', 'scale-100');
            indicator.classList.add('opacity-0', 'scale-0');
        } else {
            // Select
            selectedClients.push(clientId);
            card.classList.add('selected');
            indicator.classList.remove('opacity-0', 'scale-0');
            indicator.classList.add('opacity-100', 'scale-100');
        }
        
        updateUI();
    }
    
    function toggleManagerSelection(card) {
        const managerId = card.dataset.managerId;
        
        // Clear previous selection
        managerCards.forEach(c => c.classList.remove('selected'));
        
        if (selectedManager === managerId) {
            // Deselect
            selectedManager = null;
        } else {
            // Select
            selectedManager = managerId;
            card.classList.add('selected');
        }
        
        updateUI();
    }
    
    function updateUI() {
        // Update counts
        selectedCountEl.textContent = selectedClients.length;
        summaryClientsEl.textContent = selectedClients.length;
        
        // Update manager summary
        if (selectedManager && assignmentMode === 'manual') {
            const managerCard = document.querySelector(`.manager-card[data-manager-id="${selectedManager}"]`);
            const managerName = managerCard.querySelector('h3').textContent;
            summaryManagerEl.textContent = managerName;
        } else if (assignmentMode === 'auto') {
            summaryManagerEl.textContent = 'Auto-assigned';
        } else {
            summaryManagerEl.textContent = 'None selected';
        }
        
        // Update mode
        summaryModeEl.textContent = assignmentMode === 'manual' ? 'Manual' : 'Automatic';
        
        // Update button state
        if (assignmentMode === 'manual') {
            const canAssign = selectedClients.length > 0 && selectedManager;
            assignButton.disabled = !canAssign;
            assignButtonText.textContent = `Assign ${selectedClients.length} Client${selectedClients.length !== 1 ? 's' : ''}`;
        } else {
            assignButton.disabled = false;
            const maxAssignments = document.querySelector('input[name="max_assignments"]')?.value || 50;
            assignButtonText.textContent = `Auto-Assign up to ${maxAssignments} Clients`;
        }
    }
    
    function filterClients(searchTerm) {
        const term = searchTerm.toLowerCase();
        
        clientCards.forEach(card => {
            const searchText = card.dataset.searchText || '';
            if (searchText.includes(term)) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    }
    
    function updateAutoPreview() {
        const strategy = document.querySelector('input[name="auto_strategy"]:checked')?.value;
        const maxAssignments = document.querySelector('input[name="max_assignments"]')?.value || 50;
        const totalManagers = {{ assignment_stats.total_managers }};
        
        if (totalManagers > 0) {
            const estimatedPerManager = Math.ceil(Math.min(maxAssignments, {{ assignment_stats.total_unassigned }}) / totalManagers);
            document.getElementById('estimated-per-manager').textContent = `~${estimatedPerManager}`;
        }
        
        updateUI();
    }
    
    // Global functions
    window.setAssignmentMode = function(mode) {
        assignmentMode = mode;
        
        // Update UI
        document.getElementById('manual-mode').classList.toggle('active', mode === 'manual');
        document.getElementById('auto-mode').classList.toggle('active', mode === 'auto');
        
        document.getElementById('clients-section').classList.toggle('hidden', mode === 'auto');
        document.getElementById('auto-section').classList.toggle('hidden', mode === 'manual');
        
        // Reset selections when switching modes
        if (mode === 'auto') {
            selectedClients = [];
            selectedManager = null;
            clientCards.forEach(card => card.classList.remove('selected'));
            managerCards.forEach(card => card.classList.remove('selected'));
        }
        
        updateUI();
    };
    
    window.selectAllClients = function() {
        if (assignmentMode !== 'manual') return;
        
        const visibleCards = Array.from(clientCards).filter(card => card.style.display !== 'none');
        
        if (selectedClients.length === visibleCards.length) {
            // Deselect all
            selectedClients = [];
            visibleCards.forEach(card => {
                card.classList.remove('selected');
                const indicator = card.querySelector('.selection-indicator');
                indicator.classList.remove('opacity-100', 'scale-100');
                indicator.classList.add('opacity-0', 'scale-0');
            });
        } else {
            // Select all visible
            selectedClients = visibleCards.map(card => card.dataset.clientId);
            visibleCards.forEach(card => {
                card.classList.add('selected');
                const indicator = card.querySelector('.selection-indicator');
                indicator.classList.remove('opacity-0', 'scale-0');
                indicator.classList.add('opacity-100', 'scale-100');
            });
        }
        
        updateUI();
    };
    
    window.resetAssignment = function() {
        selectedClients = [];
        selectedManager = null;
        
        clientCards.forEach(card => {
            card.classList.remove('selected');
            const indicator = card.querySelector('.selection-indicator');
            indicator.classList.remove('opacity-100', 'scale-100');
            indicator.classList.add('opacity-0', 'scale-0');
        });
        
        managerCards.forEach(card => card.classList.remove('selected'));
        
        document.getElementById('assignment-reason').value = '';
        document.getElementById('client-search').value = '';
        
        // Reset filters
        clientCards.forEach(card => card.style.display = 'block');
        
        updateUI();
    };
    
    window.executeAssignment = function() {
        const reason = document.getElementById('assignment-reason').value;
        
        if (assignmentMode === 'manual') {
            if (selectedClients.length === 0 || !selectedManager) {
                alert('Please select clients and a manager before assigning.');
                return;
            }
            
            // Populate manual form
            document.getElementById('client_ids').value = JSON.stringify(selectedClients);
            document.getElementById('manager_id').value = selectedManager;
            document.getElementById('reason').value = reason;
            
            // Submit manual form
            document.getElementById('manual-assignment-form').submit();
        } else {
            // Auto assignment
            const strategy = document.querySelector('input[name="auto_strategy"]:checked')?.value;
            const maxAssignments = document.querySelector('input[name="max_assignments"]')?.value;
            
            if (!strategy) {
                alert('Please select an assignment strategy.');
                return;
            }
            
            // Populate auto form
            document.getElementById('auto_strategy').value = strategy;
            document.getElementById('max_assignments').value = maxAssignments;
            document.getElementById('auto_reason').value = reason;
            
            // Submit auto form
            document.getElementById('auto-assignment-form').submit();
        }
    };
});
</script>
{% endblock %}