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

{% block title %}Granular Permissions - {{ user.get_full_name }}{% endblock %}

{% block extra_css %}
<style>
    .permission-matrix {
        display: grid;
        grid-template-columns: 200px repeat(auto-fit, minmax(120px, 1fr));
        gap: 1px;
        background-color: #e5e7eb;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .matrix-header {
        background-color: #f3f4f6;
        padding: 12px 8px;
        font-weight: 600;
        text-align: center;
        font-size: 0.875rem;
    }
    
    .matrix-row-header {
        background-color: #f9fafb;
        padding: 12px;
        font-weight: 500;
        display: flex;
        align-items: center;
        border-right: 2px solid #e5e7eb;
    }
    
    .matrix-cell {
        background-color: white;
        padding: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
    }
    
    .matrix-cell.allowed {
        background-color: #ecfdf5;
        border: 1px solid #10b981;
    }
    
    .matrix-cell.denied {
        background-color: #fef2f2;
        border: 1px solid #ef4444;
    }
    
    .matrix-cell.custom-override {
        background-color: #fef3c7;
        border: 2px solid #f59e0b;
    }
    
    .permission-toggle {
        width: 20px;
        height: 20px;
        border-radius: 4px;
        border: 2px solid #d1d5db;
        cursor: pointer;
        transition: all 0.2s;
    }
    
    .permission-toggle.checked {
        background-color: #10b981;
        border-color: #10b981;
    }
    
    .permission-toggle.denied {
        background-color: #ef4444;
        border-color: #ef4444;
    }
    
    .permission-category {
        border-left: 4px solid;
        margin-bottom: 1rem;
    }
    
    .category-view { border-left-color: #3b82f6; }
    .category-create { border-left-color: #10b981; }
    .category-edit { border-left-color: #f59e0b; }
    .category-delete { border-left-color: #ef4444; }
    .category-approve { border-left-color: #8b5cf6; }
    .category-export { border-left-color: #06b6d4; }
    .category-manage { border-left-color: #6b7280; }
    .category-process { border-left-color: #ec4899; }
    
    .impact-indicator {
        position: absolute;
        top: 2px;
        right: 2px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
    }
    
    .impact-high { background-color: #ef4444; }
    .impact-medium { background-color: #f59e0b; }
    .impact-low { background-color: #10b981; }
    
    .permission-preview {
        max-height: 400px;
        overflow-y: auto;
    }
    
    .bulk-actions {
        position: sticky;
        top: 0;
        background: white;
        z-index: 10;
        border-bottom: 1px solid #e5e7eb;
        padding: 1rem;
        margin: -1rem -1rem 1rem -1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- Enhanced Header with Permission Summary -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex justify-between items-start">
                <div class="flex-1">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-shield-alt text-primary mr-2"></i>
                        Granular Permission Management
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Configure page-specific permissions for {{ user.get_full_name }} ({{ user.get_role_display }})
                    </p>
                    
                    <!-- Permission Summary Cards -->
                    <div class="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-4">
                        <div class="bg-blue-50 rounded-lg p-3">
                            <div class="text-sm font-medium text-blue-900">Total Permissions</div>
                            <div class="text-2xl font-bold text-blue-600" id="total-permissions">{{ permission_summary.total_permissions|default:0 }}</div>
                        </div>
                        <div class="bg-green-50 rounded-lg p-3">
                            <div class="text-sm font-medium text-green-900">Allowed</div>
                            <div class="text-2xl font-bold text-green-600" id="allowed-permissions">{{ permission_summary.allowed_permissions|default:0 }}</div>
                        </div>
                        <div class="bg-red-50 rounded-lg p-3">
                            <div class="text-sm font-medium text-red-900">Denied</div>
                            <div class="text-2xl font-bold text-red-600" id="denied-permissions">{{ permission_summary.denied_permissions|default:0 }}</div>
                        </div>
                        <div class="bg-yellow-50 rounded-lg p-3">
                            <div class="text-sm font-medium text-yellow-900">Custom Overrides</div>
                            <div class="text-2xl font-bold text-yellow-600" id="custom-overrides">{{ permission_summary.custom_overrides|default:0 }}</div>
                        </div>
                    </div>
                </div>
                
                <div class="flex space-x-3">
                    <button type="button" onclick="showPermissionPreview()" 
                        class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-eye mr-2"></i>
                        Preview Impact
                    </button>
                    <a href="{% url 'users:admin_list' %}"
                        class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        <span>←</span>
                        Back to Staff List
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced User Info with Role Context -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="flex-shrink-0 h-16 w-16">
                        {% if user.profile_image %}
                        <img class="h-16 w-16 rounded-full object-cover" src="{{ user.profile_image.url }}"
                            alt="{{ user.get_full_name }}">
                        {% elif user.selfie %}
                        <img class="h-16 w-16 rounded-full object-cover" src="{{ user.selfie.url }}"
                            alt="{{ user.get_full_name }}">
                        {% else %}
                        <div class="h-16 w-16 rounded-full bg-gray-300 flex items-center justify-center">
                            <span class="text-xl font-medium text-gray-700">{{ user.get_initials }}</span>
                        </div>
                        {% endif %}
                    </div>
                    <div>
                        <h4 class="text-xl font-medium text-gray-900">{{ user.get_full_name }}</h4>
                        <p class="text-sm text-gray-500">{{ user.email }}</p>
                        <p class="text-sm text-gray-500">{{ user.phone_number }}</p>
                        <div class="mt-2 flex items-center space-x-3">
                            {% if user.role == 'admin' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                <i class="fas fa-crown mr-1"></i>Admin
                            </span>
                            {% elif user.role == 'team_leader' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                <span>👔</span>Team Leader
                            </span>
                            {% elif user.role == 'loan_officer' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <i class="fas fa-handshake mr-1"></i>Loan Officer
                            </span>
                            {% elif user.role == 'secretary' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                                <i class="fas fa-user-secret mr-1"></i>Secretary
                            </span>
                            {% elif user.role == 'auditor' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                <span>🔍</span>Auditor
                            </span>
                            {% endif %}
                            
                            {% if user.branch %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                <span>🏢</span>{{ user.branch.name }}
                            </span>
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- Role Default Indicator -->
                <div class="text-right">
                    <div class="text-sm text-gray-500">Permission Source</div>
                    <div class="flex items-center space-x-2 mt-1">
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                            <span>🏷️</span>Role Default
                        </span>
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
                            <span>👤✏️</span>Custom Override
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% if messages %}
    {% for message in messages %}
    <div
        class="bg-{% if message.tags == 'error' %}red{% else %}green{% endif %}-50 border border-{% if message.tags == 'error' %}red{% else %}green{% endif %}-200 rounded-md p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <i
                    class="fas fa-{% if message.tags == 'error' %}exclamation-triangle{% else %}check-circle{% endif %} text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-400"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-700">{{ message }}
                </p>
            </div>
        </div>
    </div>
    {% endfor %}
    {% endif %}

    <!-- Permissions Form -->
    <form method="post" class="space-y-6" id="permissions-form">
        {% csrf_token %}

        <!-- Enhanced Bulk Actions with Permission Categories -->
        <div class="bg-white shadow rounded-lg">
            <div class="bulk-actions">
                <div class="flex justify-between items-center mb-4">
                    <h4 class="text-lg font-medium text-gray-900">
                        <span>⚡</span>
                        Bulk Permission Management
                    </h4>
                    <div class="flex items-center space-x-2">
                        <span class="text-sm text-gray-500">View Mode:</span>
                        <select id="view-mode" onchange="changeViewMode()" class="text-sm border-gray-300 rounded-md">
                            <option value="category">By Category</option>
                            <option value="page">By Page</option>
                            <option value="matrix">Permission Matrix</option>
                        </select>
                    </div>
                </div>
                
                <!-- Quick Action Buttons -->
                <div class="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-8">
                    <button type="button" onclick="selectAll()" class="btn-quick-action bg-green-50 text-green-700 hover:bg-green-100">
                        <i class="fas fa-check-square mr-1"></i>All
                    </button>
                    <button type="button" onclick="deselectAll()" class="btn-quick-action bg-red-50 text-red-700 hover:bg-red-100">
                        <i class="fas fa-square mr-1"></i>None
                    </button>
                    <button type="button" onclick="selectByCategory('view')" class="btn-quick-action bg-blue-50 text-blue-700 hover:bg-blue-100">
                        <i class="fas fa-eye mr-1"></i>View
                    </button>
                    <button type="button" onclick="selectByCategory('create')" class="btn-quick-action bg-green-50 text-green-700 hover:bg-green-100">
                        <span>+</span>Create
                    </button>
                    <button type="button" onclick="selectByCategory('edit')" class="btn-quick-action bg-yellow-50 text-yellow-700 hover:bg-yellow-100">
                        <span>✏️</span>Edit
                    </button>
                    <button type="button" onclick="selectByCategory('delete')" class="btn-quick-action bg-red-50 text-red-700 hover:bg-red-100">
                        <span>🗑️</span>Delete
                    </button>
                    <button type="button" onclick="selectByCategory('approve')" class="btn-quick-action bg-purple-50 text-purple-700 hover:bg-purple-100">
                        <span>✓</span>Approve
                    </button>
                    <button type="button" onclick="selectByCategory('export')" class="btn-quick-action bg-cyan-50 text-cyan-700 hover:bg-cyan-100">
                        <span>⬇️</span>Export
                    </button>
                </div>
                
                <!-- Page-Specific Quick Actions -->
                <div class="mt-4 flex flex-wrap gap-2">
                    <button type="button" onclick="selectByPage('loans')" class="btn-page-action">
                        <span>💵</span>All Loans
                    </button>
                    <button type="button" onclick="selectByPage('clients')" class="btn-page-action">
                        <span>👥</span>All Clients
                    </button>
                    <button type="button" onclick="selectByPage('reports')" class="btn-page-action">
                        <span>📊</span>All Reports
                    </button>
                    <button type="button" onclick="selectByPage('dashboard')" class="btn-page-action">
                        <i class="fas fa-tachometer-alt mr-1"></i>All Dashboard
                    </button>
                    <button type="button" onclick="selectByPage('repayments')" class="btn-page-action">
                        <span>💳</span>All Repayments
                    </button>
                </div>
            </div>
        </div>

        <!-- Granular Permission Matrix -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <h4 class="text-lg font-medium text-gray-900 mb-4">
                    <span>⚙️</span>
                    Page-Specific Permission Matrix
                </h4>
                <p class="text-sm text-gray-600 mb-6">
                    Configure granular permissions for each page and action. Custom overrides will take precedence over role defaults.
                </p>

                <!-- Permission Matrix View -->
                <div id="matrix-view" class="space-y-8">
                    {% for page_name, page_data in page_permissions.items %}
                    <div class="permission-category category-{{ page_data.primary_category|default:'view' }} bg-white border border-gray-200 rounded-lg overflow-hidden">
                        <!-- Page Header -->
                        <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center">
                                    <i class="fas fa-{{ page_data.icon|default:'cube' }} text-{{ page_data.color|default:'gray' }}-500 mr-3 text-xl"></i>
                                    <div>
                                        <h5 class="text-lg font-semibold text-gray-900">{{ page_name|title }} Page</h5>
                                        <p class="text-sm text-gray-600">{{ page_data.description|default:'Manage permissions for this page' }}</p>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <span class="text-sm text-gray-500">{{ page_data.actions|length }} permissions</span>
                                    <button type="button" onclick="togglePagePermissions('{{ page_name }}')" 
                                        class="text-xs px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200">
                                        Toggle All
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Permission Actions Grid -->
                        <div class="p-6">
                            <!-- Category Tabs -->
                            <div class="flex flex-wrap gap-2 mb-4">
                                {% for category in page_data.categories %}
                                <button type="button" onclick="filterCategory('{{ page_name }}', '{{ category }}')" 
                                    class="category-tab px-3 py-1 text-xs font-medium rounded-full border category-{{ category }}"
                                    data-page="{{ page_name }}" data-category="{{ category }}">
                                    <i class="fas fa-{{ category|category_icon }} mr-1"></i>
                                    {{ category|title }}
                                </button>
                                {% endfor %}
                            </div>
                            
                            <!-- Actions Grid -->
                            <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                {% for action_code, perm_data in page_data.actions.items %}
                                <div class="permission-item border border-gray-200 rounded-lg p-3 hover:shadow-sm transition-shadow"
                                     data-page="{{ page_name }}" data-category="{{ perm_data.category }}" data-action="{{ action_code }}">
                                    
                                    <!-- Permission Toggle -->
                                    <div class="flex items-start justify-between mb-2">
                                        <label class="flex items-center cursor-pointer flex-1">
                                            <div class="relative">
                                                <input type="checkbox" 
                                                       name="perm_{{ page_name }}_{{ action_code }}" 
                                                       {% if perm_data.allowed %}checked{% endif %}
                                                       class="permission-checkbox sr-only"
                                                       data-page="{{ page_name }}"
                                                       data-action="{{ action_code }}"
                                                       data-category="{{ perm_data.category }}"
                                                       data-critical="{{ perm_data.is_critical|yesno:'true,false' }}"
                                                       onchange="updatePermissionState(this)">
                                                <div class="permission-toggle {% if perm_data.allowed %}checked{% else %}denied{% endif %} {% if perm_data.is_custom %}custom-override{% endif %}">
                                                    <i class="fas fa-{% if perm_data.allowed %}check{% else %}times{% endif %} text-white text-xs"></i>
                                                </div>
                                            </div>
                                            <div class="ml-3 flex-1">
                                                <div class="text-sm font-medium text-gray-900">{{ perm_data.action_name }}</div>
                                                <div class="text-xs text-gray-500">{{ perm_data.description|truncatechars:60 }}</div>
                                            </div>
                                        </label>
                                        
                                        <!-- Permission Indicators -->
                                        <div class="flex items-center space-x-1 ml-2">
                                            {% if perm_data.is_critical %}
                                            <span class="impact-indicator impact-high" title="Critical Permission"></span>
                                            {% endif %}
                                            {% if perm_data.is_custom %}
                                            <span>👤✏️</span>
                                            {% else %}
                                            <span>🏷️</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    
                                    <!-- Category Badge -->
                                    <div class="flex items-center justify-between">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium category-{{ perm_data.category }}">
                                            <i class="fas fa-{{ perm_data.category|category_icon }} mr-1"></i>
                                            {{ perm_data.category|title }}
                                        </span>
                                        
                                        {% if perm_data.required_permissions %}
                                        <span>🔗</span>
                                        {% endif %}
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>

                <!-- Enhanced Legend -->
                <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-6 mt-8">
                    <h6 class="font-semibold text-blue-900 mb-4 flex items-center">
                        <span>ℹ️</span>
                        Permission System Guide
                    </h6>
                    
                    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                        <!-- Permission States -->
                        <div>
                            <h7 class="font-medium text-blue-800 mb-2 block">Permission States</h7>
                            <div class="space-y-2 text-sm text-blue-700">
                                <div class="flex items-center">
                                    <div class="permission-toggle checked w-4 h-4 mr-2"></div>
                                    <span>Allowed</span>
                                </div>
                                <div class="flex items-center">
                                    <div class="permission-toggle denied w-4 h-4 mr-2"></div>
                                    <span>Denied</span>
                                </div>
                                <div class="flex items-center">
                                    <div class="permission-toggle custom-override w-4 h-4 mr-2"></div>
                                    <span>Custom Override</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Categories -->
                        <div>
                            <h7 class="font-medium text-blue-800 mb-2 block">Permission Categories</h7>
                            <div class="space-y-1 text-sm text-blue-700">
                                <div><i class="fas fa-eye w-4 mr-2"></i>View/Access</div>
                                <div><span>+</span>Create/Add</div>
                                <div><span>✏️</span>Edit/Modify</div>
                                <div><span>🗑️</span>Delete/Remove</div>
                                <div><span>✓</span>Approve/Reject</div>
                                <div><span>⬇️</span>Export/Download</div>
                            </div>
                        </div>
                        
                        <!-- Indicators -->
                        <div>
                            <h7 class="font-medium text-blue-800 mb-2 block">Indicators</h7>
                            <div class="space-y-2 text-sm text-blue-700">
                                <div class="flex items-center">
                                    <span class="impact-indicator impact-high w-3 h-3 mr-2"></span>
                                    <span>Critical Permission</span>
                                </div>
                                <div class="flex items-center">
                                    <span>👤✏️</span>
                                    <span>Custom Override</span>
                                </div>
                                <div class="flex items-center">
                                    <span>🏷️</span>
                                    <span>Role Default</span>
                                </div>
                                <div class="flex items-center">
                                    <span>🔗</span>
                                    <span>Has Dependencies</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4 p-3 bg-blue-100 rounded-lg">
                        <p class="text-sm text-blue-800">
                            <span>💡</span>
                            <strong>Tip:</strong> Custom overrides take precedence over role defaults. Use the bulk actions above to quickly configure multiple permissions at once.
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Enhanced Submit Buttons with Validation -->
        <div class="flex justify-between items-center">
            <div class="flex items-center space-x-4">
                <button type="button" onclick="validatePermissions()" 
                    class="inline-flex items-center px-4 py-2 border border-blue-300 rounded-md shadow-sm text-sm font-medium text-blue-700 bg-blue-50 hover:bg-blue-100">
                    <span>✓</span>
                    Validate Changes
                </button>
                <button type="button" onclick="resetToRoleDefaults()" 
                    class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                    <span>↶</span>
                    Reset to Role Defaults
                </button>
            </div>
            
            <div class="flex space-x-3">
                <a href="{% url 'users:admin_list' %}"
                    class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Cancel
                </a>
                <button type="submit" id="save-permissions-btn"
                    class="inline-flex items-center px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed">
                    <span>💾</span>
                    Save Permissions
                    <span id="changes-count" class="ml-2 px-2 py-1 bg-white bg-opacity-20 rounded-full text-xs hidden">0</span>
                </button>
            </div>
        </div>
    </form>
</div>

<!-- Permission Preview Modal -->
<div id="permission-preview-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 max-w-4xl shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <!-- Modal Header -->
            <div class="flex items-center justify-between pb-4 border-b">
                <h3 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-eye mr-2 text-blue-500"></i>
                    Permission Changes Preview
                </h3>
                <button onclick="closePermissionPreview()" class="text-gray-400 hover:text-gray-600">
                    <span>✕</span>
                </button>
            </div>
            
            <!-- Modal Content -->
            <div class="mt-4 permission-preview">
                <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
                    <!-- Changes Summary -->
                    <div>
                        <h4 class="font-medium text-gray-900 mb-3">Changes Summary</h4>
                        <div class="space-y-2" id="changes-summary">
                            <!-- Dynamic content -->
                        </div>
                    </div>
                    
                    <!-- Impact Analysis -->
                    <div>
                        <h4 class="font-medium text-gray-900 mb-3">Impact Analysis</h4>
                        <div class="space-y-2" id="impact-analysis">
                            <!-- Dynamic content -->
                        </div>
                    </div>
                </div>
                
                <!-- Detailed Changes -->
                <div class="mt-6">
                    <h4 class="font-medium text-gray-900 mb-3">Detailed Changes</h4>
                    <div class="max-h-64 overflow-y-auto border border-gray-200 rounded-lg">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Page</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Action</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Change</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Impact</th>
                                </tr>
                            </thead>
                            <tbody id="detailed-changes" class="bg-white divide-y divide-gray-200">
                                <!-- Dynamic content -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Modal Footer -->
            <div class="flex justify-end space-x-3 pt-4 border-t mt-6">
                <button onclick="closePermissionPreview()" 
                    class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50">
                    Close
                </button>
                <button onclick="applyChanges()" 
                    class="px-4 py-2 bg-primary text-white rounded-md text-sm font-medium hover:bg-primary-dark">
                    Apply Changes
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    // Global state management
    let originalPermissions = {};
    let currentChanges = {};
    let validationResults = {};

    document.addEventListener('DOMContentLoaded', function () {
        initializePermissionSystem();
        setupEventListeners();
        captureOriginalState();
    });

    function initializePermissionSystem() {
        // Initialize permission toggles
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        checkboxes.forEach(checkbox => {
            updatePermissionVisual(checkbox);
        });
        
        // Initialize view mode
        changeViewMode();
        
        // Update counters
        updatePermissionCounters();
    }

    function setupEventListeners() {
        const form = document.getElementById('permissions-form');
        
        // Form submission with enhanced validation
        form.addEventListener('submit', function (e) {
            // Don't prevent default - let the form submit normally
            // Just add visual feedback
            const submitBtn = document.getElementById('save-permissions-btn');
            if (submitBtn && !submitBtn.disabled) {
                submitBtn.disabled = true;
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<span>⟳</span>Saving...';
                
                // Allow form to submit normally
                // If validation fails, re-enable button
                setTimeout(() => {
                    if (submitBtn.disabled) {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                }, 5000);
            }
        });

        // Permission checkbox changes
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                updatePermissionState(this);
                trackChange(this);
                updatePermissionCounters();
                updateChangesIndicator();
            });
        });
    }

    function captureOriginalState() {
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        checkboxes.forEach(checkbox => {
            const key = `${checkbox.dataset.page}_${checkbox.dataset.action}`;
            originalPermissions[key] = checkbox.checked;
        });
    }

    function updatePermissionState(checkbox) {
        const toggle = checkbox.parentElement.querySelector('.permission-toggle');
        const item = checkbox.closest('.permission-item');
        
        // Update visual state
        if (checkbox.checked) {
            toggle.classList.remove('denied');
            toggle.classList.add('checked');
            toggle.innerHTML = '<span>✓</span>';
            item.classList.remove('bg-red-50');
            item.classList.add('bg-green-50');
        } else {
            toggle.classList.remove('checked');
            toggle.classList.add('denied');
            toggle.innerHTML = '<span>✕</span>';
            item.classList.remove('bg-green-50');
            item.classList.add('bg-red-50');
        }
        
        // Check if this is a custom override
        const key = `${checkbox.dataset.page}_${checkbox.dataset.action}`;
        const isCustom = originalPermissions[key] !== checkbox.checked;
        
        if (isCustom) {
            toggle.classList.add('custom-override');
            item.classList.add('border-yellow-300');
        } else {
            toggle.classList.remove('custom-override');
            item.classList.remove('border-yellow-300');
        }
    }

    function trackChange(checkbox) {
        const key = `${checkbox.dataset.page}_${checkbox.dataset.action}`;
        const original = originalPermissions[key];
        
        if (original !== checkbox.checked) {
            currentChanges[key] = {
                page: checkbox.dataset.page,
                action: checkbox.dataset.action,
                from: original,
                to: checkbox.checked,
                critical: checkbox.dataset.critical === 'true'
            };
        } else {
            delete currentChanges[key];
        }
    }

    function updatePermissionCounters() {
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        let total = checkboxes.length;
        let allowed = 0;
        let denied = 0;
        let customOverrides = 0;
        
        checkboxes.forEach(checkbox => {
            if (checkbox.checked) {
                allowed++;
            } else {
                denied++;
            }
            
            const key = `${checkbox.dataset.page}_${checkbox.dataset.action}`;
            if (originalPermissions[key] !== checkbox.checked) {
                customOverrides++;
            }
        });
        
        document.getElementById('total-permissions').textContent = total;
        document.getElementById('allowed-permissions').textContent = allowed;
        document.getElementById('denied-permissions').textContent = denied;
        document.getElementById('custom-overrides').textContent = customOverrides;
    }

    function updateChangesIndicator() {
        const changesCount = Object.keys(currentChanges).length;
        const indicator = document.getElementById('changes-count');
        const submitBtn = document.getElementById('save-permissions-btn');
        
        if (changesCount > 0) {
            indicator.textContent = changesCount;
            indicator.classList.remove('hidden');
            submitBtn.classList.add('bg-yellow-500', 'hover:bg-yellow-600');
            submitBtn.classList.remove('bg-primary', 'hover:bg-primary-dark');
        } else {
            indicator.classList.add('hidden');
            submitBtn.classList.remove('bg-yellow-500', 'hover:bg-yellow-600');
            submitBtn.classList.add('bg-primary', 'hover:bg-primary-dark');
        }
    }

    // Bulk Actions
    function selectAll() {
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
            updatePermissionState(checkbox);
            trackChange(checkbox);
        });
        updatePermissionCounters();
        updateChangesIndicator();
    }

    function deselectAll() {
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            updatePermissionState(checkbox);
            trackChange(checkbox);
        });
        updatePermissionCounters();
        updateChangesIndicator();
    }

    function selectByCategory(category) {
        const checkboxes = document.querySelectorAll(`[data-category="${category}"]`);
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
            updatePermissionState(checkbox);
            trackChange(checkbox);
        });
        updatePermissionCounters();
        updateChangesIndicator();
    }

    function selectByPage(page) {
        const checkboxes = document.querySelectorAll(`[data-page="${page}"]`);
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
            updatePermissionState(checkbox);
            trackChange(checkbox);
        });
        updatePermissionCounters();
        updateChangesIndicator();
    }

    function togglePagePermissions(page) {
        const checkboxes = document.querySelectorAll(`[data-page="${page}"]`);
        const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const shouldCheck = checkedCount < checkboxes.length / 2;
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = shouldCheck;
            updatePermissionState(checkbox);
            trackChange(checkbox);
        });
        updatePermissionCounters();
        updateChangesIndicator();
    }

    // View Management
    function changeViewMode() {
        const mode = document.getElementById('view-mode').value;
        const matrixView = document.getElementById('matrix-view');
        
        // This would switch between different view modes
        // For now, we'll just log the change
        console.log('View mode changed to:', mode);
    }

    function filterCategory(page, category) {
        const items = document.querySelectorAll(`[data-page="${page}"] .permission-item`);
        const tabs = document.querySelectorAll(`[data-page="${page}"] .category-tab`);
        
        // Update tab states
        tabs.forEach(tab => {
            if (tab.dataset.category === category) {
                tab.classList.add('bg-blue-100', 'text-blue-800', 'border-blue-300');
            } else {
                tab.classList.remove('bg-blue-100', 'text-blue-800', 'border-blue-300');
            }
        });
        
        // Filter items
        items.forEach(item => {
            if (item.dataset.category === category || category === 'all') {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    }

    // Permission Preview and Validation
    function showPermissionPreview() {
        generatePreviewContent();
        document.getElementById('permission-preview-modal').classList.remove('hidden');
    }

    function closePermissionPreview() {
        document.getElementById('permission-preview-modal').classList.add('hidden');
    }

    function generatePreviewContent() {
        const changesCount = Object.keys(currentChanges).length;
        const criticalChanges = Object.values(currentChanges).filter(change => change.critical).length;
        
        // Update changes summary
        const summaryDiv = document.getElementById('changes-summary');
        summaryDiv.innerHTML = `
            <div class="bg-blue-50 p-3 rounded-lg">
                <div class="text-sm font-medium text-blue-900">Total Changes: ${changesCount}</div>
                <div class="text-xs text-blue-700">Critical Changes: ${criticalChanges}</div>
            </div>
        `;
        
        // Update impact analysis
        const impactDiv = document.getElementById('impact-analysis');
        let impactLevel = 'Low';
        let impactColor = 'green';
        
        if (criticalChanges > 0) {
            impactLevel = 'High';
            impactColor = 'red';
        } else if (changesCount > 10) {
            impactLevel = 'Medium';
            impactColor = 'yellow';
        }
        
        impactDiv.innerHTML = `
            <div class="bg-${impactColor}-50 p-3 rounded-lg">
                <div class="text-sm font-medium text-${impactColor}-900">Impact Level: ${impactLevel}</div>
                <div class="text-xs text-${impactColor}-700">
                    ${criticalChanges > 0 ? 'Contains critical permission changes' : 'Standard permission updates'}
                </div>
            </div>
        `;
        
        // Update detailed changes table
        const tableBody = document.getElementById('detailed-changes');
        tableBody.innerHTML = '';
        
        Object.values(currentChanges).forEach(change => {
            const row = document.createElement('tr');
            const changeType = change.to ? 'Granted' : 'Revoked';
            const changeColor = change.to ? 'green' : 'red';
            const impactBadge = change.critical ? '<span class="bg-red-100 text-red-800 text-xs px-2 py-1 rounded">Critical</span>' : '<span class="bg-gray-100 text-gray-800 text-xs px-2 py-1 rounded">Standard</span>';
            
            row.innerHTML = `
                <td class="px-4 py-2 text-sm text-gray-900">${change.page}</td>
                <td class="px-4 py-2 text-sm text-gray-900">${change.action}</td>
                <td class="px-4 py-2 text-sm">
                    <span class="text-${changeColor}-600 font-medium">${changeType}</span>
                </td>
                <td class="px-4 py-2">${impactBadge}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    function validatePermissions() {
        // Perform validation checks
        const issues = [];
        const checkboxes = document.querySelectorAll('.permission-checkbox');
        
        // Check for critical permissions without dependencies
        checkboxes.forEach(checkbox => {
            if (checkbox.dataset.critical === 'true' && checkbox.checked) {
                // Add validation logic here
            }
        });
        
        if (issues.length === 0) {
            alert('✅ All permissions are valid!');
        } else {
            alert('⚠️ Validation issues found:\n' + issues.join('\n'));
        }
    }

    function resetToRoleDefaults() {
        if (confirm('This will reset all permissions to the role defaults. Continue?')) {
            // Reset all checkboxes to original state
            Object.keys(originalPermissions).forEach(key => {
                const [page, action] = key.split('_');
                const checkbox = document.querySelector(`[data-page="${page}"][data-action="${action}"]`);
                if (checkbox) {
                    checkbox.checked = originalPermissions[key];
                    updatePermissionState(checkbox);
                }
            });
            
            currentChanges = {};
            updatePermissionCounters();
            updateChangesIndicator();
        }
    }

    function applyChanges() {
        closePermissionPreview();
        document.getElementById('permissions-form').submit();
    }
</script>

<style>
    /* Enhanced Button Styles */
    .btn-quick-action {
        @apply px-3 py-2 text-xs font-medium rounded-md border transition-colors duration-200 cursor-pointer;
    }
    
    .btn-page-action {
        @apply px-3 py-1 text-xs font-medium rounded-full border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 transition-colors duration-200;
    }
    
    /* Category Tab Styles */
    .category-tab {
        @apply transition-all duration-200 cursor-pointer;
        border-color: #e5e7eb;
        background-color: #f9fafb;
        color: #6b7280;
    }
    
    .category-tab:hover {
        background-color: #f3f4f6;
    }
    
    .category-tab.active {
        @apply bg-blue-100 text-blue-800 border-blue-300;
    }
    
    /* Category Icon Mapping */
    .category-view { @apply bg-blue-50 text-blue-700 border-blue-200; }
    .category-create { @apply bg-green-50 text-green-700 border-green-200; }
    .category-edit { @apply bg-yellow-50 text-yellow-700 border-yellow-200; }
    .category-delete { @apply bg-red-50 text-red-700 border-red-200; }
    .category-approve { @apply bg-purple-50 text-purple-700 border-purple-200; }
    .category-export { @apply bg-cyan-50 text-cyan-700 border-cyan-200; }
    .category-manage { @apply bg-gray-50 text-gray-700 border-gray-200; }
    .category-process { @apply bg-pink-50 text-pink-700 border-pink-200; }
    
    /* Permission Item Animations */
    .permission-item {
        @apply transition-all duration-200;
    }
    
    .permission-item:hover {
        @apply shadow-md transform scale-105;
    }
    
    .permission-item.bg-green-50 {
        @apply border-green-200;
    }
    
    .permission-item.bg-red-50 {
        @apply border-red-200;
    }
    
    /* Modal Animations */
    #permission-preview-modal {
        animation: fadeIn 0.3s ease-out;
    }
    
    #permission-preview-modal > div {
        animation: slideIn 0.3s ease-out;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    @keyframes slideIn {
        from { transform: translateY(-20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }
    
    /* Loading States */
    .loading {
        @apply opacity-50 pointer-events-none;
    }
    
    .loading::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 20px;
        height: 20px;
        margin: -10px 0 0 -10px;
        border: 2px solid #f3f3f3;
        border-top: 2px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* Responsive Adjustments */
    @media (max-width: 640px) {
        .permission-matrix {
            grid-template-columns: 150px repeat(auto-fit, minmax(100px, 1fr));
        }
        
        .matrix-header {
            padding: 8px 4px;
            font-size: 0.75rem;
        }
        
        .matrix-row-header {
            padding: 8px;
            font-size: 0.875rem;
        }
        
        .permission-item {
            padding: 12px;
        }
        
        .btn-quick-action {
            @apply px-2 py-1 text-xs;
        }
    }
    
    /* Print Styles */
    @media print {
        .bulk-actions,
        .btn-quick-action,
        .btn-page-action,
        #permission-preview-modal {
            display: none !important;
        }
        
        .permission-item {
            break-inside: avoid;
        }
    }
</style>
{% endblock %}