<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
{% extends "base.html" %}

{% block title %}User Management - AISBF Dashboard{% endblock %}

{% block content %}
<h2 style="margin-bottom: 30px;" data-i18n="users_page.title">User Management</h2>

<div id="url-data" data-base-url="{{ url_for(request, '/dashboard/users/') }}" style="display:none;"></div>

{% if success %}
<div class="alert alert-success">{{ success }}</div>
{% endif %}

{% if error %}
<div class="alert alert-error">{{ error }}</div>
{% endif %}

<!-- Add New User Form -->
<div style="margin-bottom: 30px; padding: 20px; background: var(--bg-accent); border-radius: 8px;">
    <h3 style="margin-bottom: 15px;" data-i18n="users_page.add_user">Add New User</h3>
    <form method="POST" action="{{ url_for(request, '/dashboard/users/add') }}" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end;">
        <div class="form-group" style="flex: 1; min-width: 200px; margin-bottom: 0;">
            <label for="username" data-i18n="users_page.username">Username</label>
            <input type="text" id="username" name="username" required style="width: 100%; background: var(--bg-page) !important; color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px;">
        </div>
        <div class="form-group" style="flex: 1; min-width: 200px; margin-bottom: 0;">
            <label for="email" data-i18n="users_page.email">Email</label>
            <input type="email" id="email" name="email" style="width: 100%; background: var(--bg-page) !important; color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px;">
        </div>
        <div class="form-group" style="flex: 1; min-width: 200px; margin-bottom: 0;">
            <label for="password" data-i18n="users_page.password">Password</label>
            <input type="password" id="password" name="password" required style="width: 100%; background: var(--bg-page) !important; color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px;">
        </div>
        <div class="form-group" style="flex: 0 0 150px; margin-bottom: 0;">
            <label for="role" data-i18n="users_page.role">Role</label>
            <select id="role" name="role" style="width: 100%; background: var(--bg-page) !important; color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px;">
                <option value="user">User</option>
                <option value="admin">Admin</option>
            </select>
        </div>
        <button type="submit" class="btn">Add User</button>
    </form>
</div>

<!-- Search and Filter Controls -->
<div style="margin-bottom: 20px; padding: 15px; background: var(--bg-accent); border-radius: 8px;">
    <div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
        <div style="flex: 1; min-width: 200px;">
            <label for="search-input" style="display: block; margin-bottom: 5px; color: var(--color-text);" data-i18n="users_page.search_users">Search Users</label>
            <input type="text" id="search-input" data-i18n="users_page.search_placeholder" placeholder="Search by username, email, or display name..."
                   value="{{ filters.search }}" style="width: 100%; padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
        </div>

        <div style="display: flex; gap: 10px; align-items: center;">
            <label for="status-filter" style="color: var(--color-text); margin-right: 5px;" data-i18n="users_page.status">Status:</label>
            <select id="status-filter" style="padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                <option value="" data-i18n="users_page.status_all">All</option>
                <option value="active" {% if filters.status_filter == 'active' %}selected{% endif %} data-i18n="users_page.status_active">Active</option>
                <option value="inactive" {% if filters.status_filter == 'inactive' %}selected{% endif %} data-i18n="users_page.status_inactive">Inactive</option>
            </select>

            <label for="role-filter" style="color: var(--color-text); margin-left: 10px; margin-right: 5px;" data-i18n="users_page.role_filter">Role:</label>
            <select id="role-filter" style="padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                <option value="">All</option>
                <option value="admin" {% if filters.role_filter == 'admin' %}selected{% endif %}>Admin</option>
                <option value="user" {% if filters.role_filter == 'user' %}selected{% endif %}>User</option>
            </select>

            <label for="tier-filter" style="color: var(--color-text); margin-left: 10px; margin-right: 5px;" data-i18n="users_page.col_tier">Tier:</label>
            <select id="tier-filter" style="padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                <option value="">All</option>
                {% for tier in tiers %}
                <option value="{{ tier.id }}" {% if filters.tier_filter == tier.id|string %}selected{% endif %}>
                    {{ tier.name }}{% if not tier.is_visible %} (Hidden){% endif %}
                </option>
                {% endfor %}
            </select>

            <label for="market-export-filter" style="color: var(--color-text); margin-left: 10px; margin-right: 5px;">Market:</label>
            <select id="market-export-filter" style="padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                <option value="">All</option>
                <option value="exporting" {% if filters.market_export_filter == 'exporting' %}selected{% endif %}>Exporting</option>
                <option value="not_exporting" {% if filters.market_export_filter == 'not_exporting' %}selected{% endif %}>Not Exporting</option>
            </select>

            <button id="search-btn" class="btn" style="padding: 8px 16px;" data-i18n="users_page.search_btn">Search</button>
            <button id="clear-btn" class="btn btn-secondary" style="padding: 8px 16px;" data-i18n="users_page.clear_btn">Clear</button>
        </div>
    </div>
</div>

<!-- Users Table -->
<h3 style="margin-bottom: 15px;" data-i18n="users_page.all_users">All Users</h3>

<!-- Bulk Actions Bar -->
<div id="bulk-actions" style="display: none; margin-bottom: 20px; padding: 15px; background: var(--bg-accent); border-radius: 8px;">
    <div style="display: flex; justify-content: space-between; align-items: center;">
        <div style="color: var(--color-text);">
            <span id="selected-count">0</span> users selected
        </div>

        <div style="display: flex; gap: 10px; align-items: center;">
            <select id="bulk-tier-select" style="padding: 8px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                {% for tier in tiers %}
                <option value="{{ tier.id }}">{{ tier.name }}{% if not tier.is_visible %} (Hidden){% endif %}</option>
                {% endfor %}
            </select>
            <button id="bulk-enable" class="btn" data-i18n="users_page.enable_selected">Enable Selected</button>
            <button id="bulk-disable" class="btn" data-i18n="users_page.disable_selected">Disable Selected</button>
            <button id="bulk-delete" class="btn btn-danger" data-i18n="users_page.delete_selected">Delete Selected</button>
            <button id="bulk-notify" class="btn btn-secondary" style="background:#7c3aed;"><i class="fas fa-bell"></i> Send Notification</button>
            <button id="bulk-clear" class="btn btn-secondary" data-i18n="users_page.clear_selection">Clear Selection</button>
        </div>
    </div>
</div>

<table>
    <thead>
        <tr>
            <th style="width: 40px;">
                <input type="checkbox" id="select-all" title="Select all visible users">
            </th>
            <th>ID</th>
            <th class="sortable" data-column="username">
                Username
                <span class="sort-indicator" data-column="username">
                    {% if filters.order_by == 'username' %}
                        {% if filters.direction == 'asc' %}▲{% else %}▼{% endif %}
                    {% endif %}
                </span>
            </th>
            <th data-i18n="users_page.col_email">Email</th>
            <th data-i18n="users_page.col_role">Role</th>
            <th data-i18n="users_page.col_tier">Tier</th>
            <th data-i18n="users_page.col_created_by">Created By</th>
            <th class="sortable" data-column="created_at">
                Created At
                <span class="sort-indicator" data-column="created_at">
                    {% if filters.order_by == 'created_at' %}
                        {% if filters.direction == 'asc' %}▲{% else %}▼{% endif %}
                    {% endif %}
                </span>
            </th>
            <th class="sortable" data-column="last_login">
                Last Login
                <span class="sort-indicator" data-column="last_login">
                    {% if filters.order_by == 'last_login' %}
                        {% if filters.direction == 'asc' %}▲{% else %}▼{% endif %}
                    {% endif %}
                </span>
            </th>
            <th data-i18n="users_page.col_active">Active</th>
            <th data-i18n="users_page.col_actions">Actions</th>
        </tr>
    </thead>
    <tbody>
        {% if users %}
            {% for user in users %}
            <tr>
                <td>
                    <input type="checkbox" class="user-checkbox" value="{{ user.id }}" title="Select user {{ user.display_name or user.username }}">
                </td>
                <td>{{ user.id }}</td>
                <td>{{ user.display_name or user.username }}</td>
                <td>{{ user.email or '-' }}</td>
                <td>
                    {% if user.role == 'admin' %}
                    <span style="color: var(--color-primary); font-weight: bold;" data-i18n="users_page.role_admin_label">Admin</span>
                    {% else %}
                    <span style="color: var(--color-muted);" data-i18n="users_page.role_user_label">User</span>
                    {% endif %}
                </td>
                <td>
                    <select onchange="updateUserTier({{ user.id }}, this.value)" style="background: var(--bg-page); color: var(--color-text); border: 1px solid var(--bg-accent); padding: 5px; border-radius: 3px;">
                        {% for tier in tiers %}
                        <option value="{{ tier.id }}" {% if user.tier_id == tier.id %}selected{% endif %}>
                            {{ tier.name }}{% if not tier.is_visible %} (Hidden){% endif %}
                        </option>
                        {% endfor %}
                    </select>
                </td>
                <td>{{ user.created_by or '-' }}</td>
                <td>{{ user.created_at }}</td>
                <td>{{ user.last_login or 'Never' }}</td>
                <td>
                    {% if user.is_active %}
                    <span style="color: #4ade80;" data-i18n="users_page.active_yes">Yes</span>
                    {% else %}
                    <span style="color: var(--alert-error-fg);">No</span>
                    {% endif %}
                </td>
                <td>
                    <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                        <button onclick="editUser({{ user.id }}, '{{ user.username }}', '{{ user.email }}', '{{ user.role }}', {{ user.is_active|lower }})" class="btn btn-secondary" style="padding: 5px 10px; font-size: 12px; margin: 0;" data-i18n="users_page.edit_btn">Edit</button>
                        <button onclick="toggleUserStatus({{ user.id }}, {{ user.is_active|lower }})" class="btn btn-warning" style="padding: 5px 10px; font-size: 12px; margin: 0;">
                            {% if user.is_active %}Disable{% else %}Enable{% endif %}
                        </button>
                        <button onclick="impersonateUser({{ user.id }}, '{{ user.username }}')" class="btn" style="padding: 5px 10px; font-size: 12px; margin: 0; background: #7c3aed;">Impersonate</button>
                        <button onclick="deleteUser({{ user.id }}, '{{ user.username }}')" class="btn btn-danger" style="padding: 5px 10px; font-size: 12px; margin: 0;" data-i18n="users_page.delete_btn">Delete</button>
                    </div>
                </td>
            </tr>
            {% endfor %}
        {% else %}
            <tr>
                <td colspan="11" style="text-align: center; color: var(--color-subtle);" data-i18n="users_page.no_users">No users found</td>
            </tr>
        {% endif %}
    </tbody>
</table>

<!-- Pagination Controls -->
{% if pagination.total_pages > 1 %}
<div id="pagination-controls" style="margin-top: 20px; padding: 15px; background: var(--bg-accent); border-radius: 8px;">
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
        <div style="color: var(--color-text);">
            Showing {{ pagination.start_item }}-{{ pagination.end_item }} of {{ pagination.total_users }} users
        </div>

        <div style="display: flex; gap: 10px; align-items: center;">
            <label for="page-size" style="color: var(--color-text); margin-right: 5px;" data-i18n="users_page.show">Show:</label>
            <select id="page-size" style="padding: 5px; border-radius: 4px; border: 1px solid var(--bg-accent); background: var(--bg-page); color: var(--color-text);">
                <option value="10" {% if pagination.limit == 10 %}selected{% endif %}>10</option>
                <option value="25" {% if pagination.limit == 25 %}selected{% endif %}>25</option>
                <option value="50" {% if pagination.limit == 50 %}selected{% endif %}>50</option>
                <option value="100" {% if pagination.limit == 100 %}selected{% endif %}>100</option>
            </select>

            <div style="display: flex; gap: 5px;">
                <button id="prev-btn" class="btn btn-secondary" {% if not pagination.has_prev %}disabled{% endif %} style="padding: 8px 12px;">
                    ← Previous
                </button>

                <span style="color: var(--color-text); padding: 8px 12px; background: var(--bg-page); border-radius: 4px;">
                    Page {{ pagination.current_page }} of {{ pagination.total_pages }}
                </span>

                <button id="next-btn" class="btn btn-secondary" {% if not pagination.has_next %}disabled{% endif %} style="padding: 8px 12px;">
                    Next →
                </button>
            </div>
        </div>
    </div>
</div>
{% endif %}

<!-- Edit User Modal -->
<div id="edit-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000;">
    <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: var(--bg-panel); padding: 30px; border-radius: 8px; width: 90%; max-width: 500px;">
        <h3 style="margin-bottom: 20px;" data-i18n="users_page.edit_title">Edit User</h3>
        <form id="edit-form" method="POST">
            <input type="hidden" id="edit-user-id" name="user_id">
            <div class="form-group">
                <label for="edit-username" data-i18n="users_page.username">Username</label>
                <input type="text" id="edit-username" name="username" required style="background: var(--bg-page); color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px; width: 100%;">
            </div>
            <div class="form-group">
                <label for="edit-email" data-i18n="users_page.email">Email</label>
                <input type="email" id="edit-email" name="email" style="background: var(--bg-page); color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px; width: 100%;">
            </div>
            <div class="form-group">
                <label for="edit-password" data-i18n="users_page.new_password">New Password (leave blank to keep current)</label>
                <input type="password" id="edit-password" name="password" placeholder="Enter new password" style="background: var(--bg-page); color: var(--color-text); border: 1px solid var(--bg-accent); padding: 8px; border-radius: 3px; width: 100%;">
            </div>
            <div class="form-group">
                <label for="edit-role" data-i18n="users_page.role">Role</label>
                <select id="edit-role" name="role">
                    <option value="user" data-i18n="users_page.role_user">User</option>
                    <option value="admin" data-i18n="users_page.role_admin">Admin</option>
                </select>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" id="edit-is-active" name="is_active" value="1">
                    <span data-i18n="users_page.col_active">Active</span>
                </label>
            </div>
            <div style="display: flex; gap: 10px;">
                <button type="submit" class="btn" data-i18n="users_page.save_changes">Save Changes</button>
                <button type="button" onclick="closeEditModal()" class="btn btn-secondary" data-i18n="modal.cancel">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
// Utility functions
const BASE_PATH = {{ request.scope.get('root_path', '') | tojson }};
const baseUrl = document.getElementById('url-data').dataset.baseUrl;
function getUrlParams() {
    const params = new URLSearchParams(window.location.search);
    return {
        search: params.get('search') || '',
        order_by: params.get('order_by') || 'created_at',
        direction: params.get('direction') || 'desc',
        page: parseInt(params.get('page')) || 1,
        limit: parseInt(params.get('limit')) || 25
    };
}

// Main function to update users list via AJAX
function updateUsers(params) {
    // Show loading state
    const tableContainer = document.querySelector('table').parentElement;
    const originalContent = tableContainer.innerHTML;
    tableContainer.innerHTML = '<div style="text-align: center; padding: 20px; color: var(--color-text);"><div class="spinner"></div> ' + window.i18n.t('users.loading') + '</div>';

    // Build query parameters
    const currentParams = new URLSearchParams(window.location.search);
    Object.keys(params).forEach(key => {
        if (params[key] !== '' && params[key] !== null && params[key] !== undefined) {
            currentParams.set(key, params[key]);
        } else {
            currentParams.delete(key);
        }
    });

    // Reset to page 1 if search/sort changed
    if (params.search !== undefined || params.order_by !== undefined) {
        currentParams.set('page', '1');
    }

    // Update URL without reload
    const newURL = window.location.pathname + (currentParams.toString() ? '?' + currentParams.toString() : '');
    window.history.pushState({}, '', newURL);

    // Fetch updated content
    fetch(newURL, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.text())
    .then(html => {
        // Parse and update just the table and pagination
        const parser = new DOMParser();
        const newDoc = parser.parseFromString(html, 'text/html');

        const newTable = newDoc.querySelector('table');
        const newPagination = newDoc.querySelector('[style*="margin-top: 20px"]');

        tableContainer.innerHTML = originalContent;
        document.querySelector('table').replaceWith(newTable);

        // Reset select-all state
        const selectAll = document.getElementById('select-all');
        if (selectAll) {
            selectAll.checked = false;
            selectAll.indeterminate = false;
        }
        updateBulkActionsVisibility();

        const existingPagination = document.querySelector('[style*="margin-top: 20px"]');
        if (existingPagination) {
            existingPagination.replaceWith(newPagination);
        } else if (newPagination) {
            document.querySelector('table').after(newPagination);
        }

        // Reattach event listeners after DOM update
        attachEventListeners();
    })
    .catch(error => {
        console.error('Error updating users:', error);
        tableContainer.innerHTML = originalContent;
        showNotification(window.i18n.t('users.error_loading'), 'error');
    });
}

// Search functionality with AJAX
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const clearBtn = document.getElementById('clear-btn');
    const statusFilter = document.getElementById('status-filter');
    const roleFilter = document.getElementById('role-filter');
    const tierFilter = document.getElementById('tier-filter');
    const marketExportFilter = document.getElementById('market-export-filter');
    const pageSize = document.getElementById('page-size');
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');

    let searchTimeout = null;

    // Main function to update users list via AJAX
    function updateUsers(params) {
        // Show loading state
        const tableContainer = document.querySelector('table').parentElement;
        const originalContent = tableContainer.innerHTML;
        tableContainer.innerHTML = '<div style="text-align: center; padding: 20px; color: var(--color-text);"><div class="spinner"></div> ' + window.i18n.t('users.loading') + '</div>';

        // Build query parameters
        const currentParams = new URLSearchParams(window.location.search);
        Object.keys(params).forEach(key => {
            if (params[key] !== '' && params[key] !== null && params[key] !== undefined) {
                currentParams.set(key, params[key]);
            } else {
                currentParams.delete(key);
            }
        });

        // Reset to page 1 if search/sort changed
        if (params.search !== undefined || params.order_by !== undefined) {
            currentParams.set('page', '1');
        }

        // Update URL without reload
        const newURL = window.location.pathname + (currentParams.toString() ? '?' + currentParams.toString() : '');
        window.history.pushState({}, '', newURL);

        // Fetch updated content
        fetch(newURL, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.text())
        .then(html => {
            // Parse and update just the table and pagination
            const parser = new DOMParser();
            const newDoc = parser.parseFromString(html, 'text/html');

            const newTable = newDoc.querySelector('table');
            const newPagination = newDoc.getElementById('pagination-controls');

            tableContainer.innerHTML = originalContent;
            document.querySelector('table').replaceWith(newTable);

            const existingPagination = document.getElementById('pagination-controls');
            if (existingPagination && newPagination) {
                existingPagination.replaceWith(newPagination);
            } else if (newPagination) {
                document.querySelector('table').after(newPagination);
            }

            // Reset select-all state
            const selectAll = document.getElementById('select-all');
            if (selectAll) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            }
            updateBulkActionsVisibility();

            // Re-attach event listeners to new elements
            attachPaginationListeners();
            attachSortingListeners();

            // Reattach select-all listener
            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.user-checkbox');
                    checkboxes.forEach(cb => cb.checked = this.checked);
                    updateBulkActionsVisibility();
                });
            }

            // Reattach individual checkbox listeners
            document.querySelectorAll('.user-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    updateBulkActionsVisibility();
                    updateSelectAllState();
                });
            });
        })
        .catch(error => {
            console.error('Error updating users:', error);
            tableContainer.innerHTML = originalContent;
            showNotification(window.i18n.t('users.error_loading'), 'error');
        });
    }

    // Attach pagination event listeners
    function attachPaginationListeners() {
        const newPageSize = document.getElementById('page-size');
        const newPrevBtn = document.getElementById('prev-btn');
        const newNextBtn = document.getElementById('next-btn');

        if (newPageSize) {
            newPageSize.addEventListener('change', function() {
                updateUsers({ limit: this.value, page: 1 });
            });
        }

        if (newPrevBtn) {
            newPrevBtn.addEventListener('click', function() {
                const params = getUrlParams();
                updateUsers({ page: Math.max(1, params.page - 1) });
            });
        }

        if (newNextBtn) {
            newNextBtn.addEventListener('click', function() {
                const params = getUrlParams();
                updateUsers({ page: params.page + 1 });
            });
        }
    }

    // Attach sorting event listeners
    function attachSortingListeners() {
        document.querySelectorAll('.sortable').forEach(header => {
            header.style.cursor = 'pointer';
            header.addEventListener('click', function() {
                const column = this.getAttribute('data-column');
                const params = getUrlParams();
                
                // Toggle direction if clicking same column, otherwise default to desc
                if (params.order_by === column) {
                    params.direction = params.direction === 'asc' ? 'desc' : 'asc';
                } else {
                    params.order_by = column;
                    params.direction = 'desc';
                }
                updateUsers({ order_by: params.order_by, direction: params.direction, page: 1 });
            });
        });
    }

    // Debounced search input
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                updateUsers({ search: searchInput.value.trim(), page: 1 });
            }, 300);
        });

        // Search on Enter key (immediate)
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                clearTimeout(searchTimeout);
                updateUsers({ search: searchInput.value.trim(), page: 1 });
            }
        });
    }

    // Search button click
    if (searchBtn) {
        searchBtn.addEventListener('click', function() {
            clearTimeout(searchTimeout);
            if (searchInput) {
                updateUsers({ search: searchInput.value.trim(), page: 1 });
            }
        });
    }

    // Clear button click
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            if (searchInput) {
                searchInput.value = '';
            }
            if (statusFilter) {
                statusFilter.value = '';
            }
            if (roleFilter) {
                roleFilter.value = '';
            }
            if (tierFilter) {
                tierFilter.value = '';
            }
            if (marketExportFilter) {
                marketExportFilter.value = '';
            }
            updateUsers({
                search: '',
                status_filter: null,
                role_filter: null,
                tier_filter: null,
                market_export_filter: null,
                page: 1,
            });
        });
    }

    // Filter change handlers
    if (statusFilter) {
        statusFilter.addEventListener('change', function() {
            updateUsers({ status_filter: this.value || null });
        });
    }

    if (roleFilter) {
        roleFilter.addEventListener('change', function() {
            updateUsers({ role_filter: this.value || null });
        });
    }

    if (tierFilter) {
        tierFilter.addEventListener('change', function() {
            updateUsers({ tier_filter: this.value || null });
        });
    }

    if (marketExportFilter) {
        marketExportFilter.addEventListener('change', function() {
            updateUsers({ market_export_filter: this.value || null });
        });
    }

    // Initial sorting listeners
    attachSortingListeners();

    // Initial pagination listeners
    attachPaginationListeners();

    // Bulk selection handlers
    document.getElementById('select-all').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.user-checkbox');
        checkboxes.forEach(cb => cb.checked = this.checked);
        updateBulkActionsVisibility();
    });

    // Individual checkbox change handlers
    document.querySelectorAll('.user-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateBulkActionsVisibility();
            updateSelectAllState();
        });
    });

    // Bulk action button handlers
    document.getElementById('bulk-enable')?.addEventListener('click', function() {
        performBulkAction('enable', 'enable these users');
    });

    document.getElementById('bulk-disable')?.addEventListener('click', function() {
        performBulkAction('disable', 'disable these users');
    });

    document.getElementById('bulk-delete')?.addEventListener('click', function() {
        performBulkAction('delete', 'delete these users', true);
    });

    document.getElementById('bulk-clear')?.addEventListener('click', function() {
        clearSelection();
    });
});

// Function to attach event listeners to dynamic elements
function attachEventListeners() {
    // Reattach sortable header listeners
    document.querySelectorAll('.sortable').forEach(header => {
        header.addEventListener('click', function() {
            const column = this.dataset.column;
            const currentOrder = getUrlParams().order_by;
            const currentDir = getUrlParams().direction || 'desc';

            let newDir = 'asc';
            if (currentOrder === column && currentDir === 'asc') {
                newDir = 'desc';
            }

            updateUsers({ order_by: column, direction: newDir });
        });
    });

    // Reattach pagination listeners
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');
    const pageSize = document.getElementById('page-size');

    if (prevBtn) {
        prevBtn.addEventListener('click', function() {
            const currentPage = parseInt(getUrlParams().page) || 1;
            if (currentPage > 1) {
                updateUsers({ page: currentPage - 1 });
            }
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', function() {
            const currentPage = parseInt(getUrlParams().page) || 1;
            updateUsers({ page: currentPage + 1 });
        });
    }

    if (pageSize) {
        pageSize.addEventListener('change', function() {
            updateUsers({ limit: this.value, page: 1 });
        });
    }

    // Reattach select-all listener
    const selectAll = document.getElementById('select-all');
    if (selectAll) {
        selectAll.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.user-checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
            updateBulkActionsVisibility();
        });
    }

    // Reattach individual checkbox listeners
    document.querySelectorAll('.user-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateBulkActionsVisibility();
            updateSelectAllState();
        });
    });
}

function updateBulkActionsVisibility() {
    const selectedCount = document.querySelectorAll('.user-checkbox:checked').length;
    const bulkActions = document.getElementById('bulk-actions');
    const selectedCountEl = document.getElementById('selected-count');

    if (selectedCount > 0) {
        bulkActions.style.display = 'block';
        selectedCountEl.textContent = selectedCount;
    } else {
        bulkActions.style.display = 'none';
    }
}

function updateSelectAllState() {
    const checkboxes = document.querySelectorAll('.user-checkbox');
    const selectAll = document.getElementById('select-all');
    const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');

    selectAll.checked = checkboxes.length > 0 && checkedBoxes.length === checkboxes.length;
    selectAll.indeterminate = checkedBoxes.length > 0 && checkedBoxes.length < checkboxes.length;
}

function clearSelection() {
    document.querySelectorAll('.user-checkbox, #select-all').forEach(cb => {
        cb.checked = false;
        cb.indeterminate = false;
    });
    updateBulkActionsVisibility();
}

async function performBulkAction(action, description, destructive = false, extraData = null) {
    const selectedIds = Array.from(document.querySelectorAll('.user-checkbox:checked')).map(cb => parseInt(cb.value));

    if (selectedIds.length === 0) {
        showNotification('No users selected', 'error');
        return;
    }

    if (destructive) {
        const ok = await showDangerConfirm(`Are you sure you want to ${description}? This action cannot be undone.`, 'Confirm Action');
        if (!ok) return;
    }

    // Show loading state
    const bulkActions = document.getElementById('bulk-actions');
    const originalContent = bulkActions.innerHTML;
    bulkActions.innerHTML = '<div style="text-align: center; padding: 10px; color: var(--color-text);"><div class="spinner"></div> ' + window.i18n.t('users.processing') + '</div>';

    // Prepare request data
    const requestData = {
        action: action,
        user_ids: selectedIds
    };
    if (extraData) {
        requestData.extra_data = extraData;
    }

    fetch(`${BASE_PATH}/dashboard/users/bulk`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message || `Successfully ${action}d ${selectedIds.length} users`, 'success');
            clearSelection();
            // Refresh the current page data
            updateUsers({});
        } else {
            showNotification(data.error || 'Bulk operation failed', 'error');
            bulkActions.innerHTML = originalContent;
        }
    })
    .catch(error => {
        console.error('Bulk action error:', error);
        showNotification('Error performing bulk action', 'error');
        bulkActions.innerHTML = originalContent;
    });
}

function editUser(userId, username, email, role, isActive) {
    document.getElementById('edit-user-id').value = userId;
    document.getElementById('edit-username').value = username;
    document.getElementById('edit-email').value = email;
    document.getElementById('edit-role').value = role;
    document.getElementById('edit-is-active').checked = isActive;
    document.getElementById('edit-form').action = baseUrl + userId + '/edit';
    document.getElementById('edit-modal').style.display = 'block';
}

function closeEditModal() {
    document.getElementById('edit-modal').style.display = 'none';
}

async function toggleUserStatus(userId, currentStatus) {
    const action = currentStatus ? 'disable' : 'enable';
    const ok = await showConfirm('Are you sure you want to ' + action + ' this user?', 'Confirm');
    if (ok) {
        fetch(baseUrl + userId + '/toggle', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                showAlert(data.error || 'Failed to toggle user status', 'Error', '❌', 'danger');
            }
        })
        .catch(error => {
            showAlert('Error: ' + error, 'Error', '❌', 'danger');
        });
    }
}

async function deleteUser(userId, username) {
    const ok = await showDangerConfirm('Are you sure you want to delete user "' + username + '"? This action cannot be undone.', 'Delete User');
    if (ok) {
        fetch(baseUrl + userId + '/delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                showAlert(data.error || 'Failed to delete user', 'Error', '❌', 'danger');
            }
        })
        .catch(error => {
            showAlert('Error: ' + error, 'Error', '❌', 'danger');
        });
    }
}

async function impersonateUser(userId, username) {
    const ok = await showConfirm('Impersonate "' + username + '"? You will act as this user until you log out, which will return you to the admin session.', 'Impersonate User', 'Impersonate', 'btn-warning');
    if (!ok) return;
    fetch(baseUrl + userId + '/impersonate', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.href = data.redirect;
        } else {
            showAlert(data.error || 'Failed to impersonate user', 'Error', '❌', 'danger');
        }
    })
    .catch(error => showAlert('Error: ' + error, 'Error', '❌', 'danger'));
}

function updateUserTier(userId, tierId) {
    fetch(baseUrl + userId + '/tier', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ tier_id: parseInt(tierId) })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success notification
            showNotification(window.i18n.t('users.tier_updated'), 'success');
        } else {
            // Show error notification
            showNotification(data.error || window.i18n.t('users.tier_update_failed'), 'error');
            location.reload(); // Reload to reset dropdown
        }
    })
    .catch(error => {
        showNotification(window.i18n.t('users.network_error'), 'error');
        location.reload(); // Reload to reset dropdown
    });
}

function showNotification(message, type) {
    // Remove any existing notifications
    const existingNotifications = document.querySelectorAll('.notification-toast');
    existingNotifications.forEach(notification => notification.remove());

    // Create new notification
    const notification = document.createElement('div');
    notification.className = `notification-toast alert alert-${type === 'success' ? 'success' : 'error'}`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
        max-width: 500px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.5);
        border: none;
        animation: slideIn 0.3s ease-out;
    `;

    notification.innerHTML = `
        <div style="display: flex; align-items: center; gap: 10px;">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}" style="font-size: 18px;"></i>
            <span>${message}</span>
        </div>
    `;

    document.body.appendChild(notification);

    // Auto-remove after 3 seconds
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-in';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('edit-modal');
    if (event.target === modal) {
        closeEditModal();
    }
}
</script>

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid var(--bg-accent);
}
th {
    background: var(--bg-accent);
    font-weight: 600;
}

/* Sortable header styles */
.sortable {
    cursor: pointer;
    user-select: none;
    position: relative;
}

.sortable:hover {
    background: var(--color-secondary-hover);
}

.sort-indicator {
    margin-left: 5px;
    font-size: 10px;
    color: var(--color-link);
}

/* Loading spinner */
.spinner {
    border: 3px solid var(--bg-accent);
    border-top: 3px solid #4ade80;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: spin 1s linear infinite;
    display: inline-block;
    margin-right: 10px;
    vertical-align: middle;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Notification animations */
@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOut {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

/* Custom alert styles */
.alert-success {
    background-color: var(--alert-success-bg) !important;
    color: var(--alert-success-fg) !important;
    border-color: var(--alert-success-border) !important;
}

.alert-error {
    background-color: var(--alert-error-bg) !important;
    color: var(--alert-error-fg) !important;
    border-color: var(--alert-error-border) !important;
}

/* Prevent browser autofill from overriding dark theme */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    -webkit-box-shadow: 0 0 0 30px var(--bg-page) inset !important;
    -webkit-text-fill-color: var(--color-text) !important;
}
</style>

<!-- Send Notification Modal -->
<div id="notify-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:1000; align-items:center; justify-content:center;">
    <div style="background:var(--bg-panel); padding:30px; border-radius:8px; width:90%; max-width:520px; border:1px solid var(--bg-accent);">
        <h3 style="margin-bottom:20px;"><i class="fas fa-bell" style="color:#a78bfa;"></i> <span data-i18n="users_page.send_notification">Send Notification</span></h3>
        <p id="notify-target-label" style="color:var(--color-muted); margin-bottom:16px; font-size:13px;"></p>
        <div class="form-group">
            <label for="notify-title" data-i18n="users_page.notify_title">Title</label>
            <input type="text" id="notify-title" maxlength="200" data-i18n="users_page.notify_title_placeholder" placeholder="Notification title"
                   style="background:var(--bg-page); color:var(--color-text); border:1px solid var(--bg-accent); padding:8px; border-radius:3px; width:100%;">
        </div>
        <div class="form-group">
            <label for="notify-message" data-i18n="users_page.notify_message">Message</label>
            <textarea id="notify-message" rows="4" data-i18n="users_page.notify_message_placeholder" placeholder="Notification message…"
                      style="background:var(--bg-page); color:var(--color-text); border:1px solid var(--bg-accent); padding:8px; border-radius:3px; width:100%; resize:vertical;"></textarea>
        </div>
        <div style="display:flex; gap:10px; margin-top:10px;">
            <button class="btn" onclick="submitNotification()"><i class="fas fa-paper-plane"></i> <span data-i18n="users_page.send_btn">Send</span></button>
            <button class="btn btn-secondary" onclick="closeNotifyModal()" data-i18n="modal.cancel">Cancel</button>
        </div>
        <div id="notify-status" style="margin-top:12px;"></div>
    </div>
</div>

<script>
let _notifyUserIds = [];

function openNotifyModal(userIds) {
    _notifyUserIds = userIds;
    document.getElementById('notify-title').value = '';
    document.getElementById('notify-message').value = '';
    document.getElementById('notify-status').innerHTML = '';
    document.getElementById('notify-target-label').textContent =
        `Sending to ${userIds.length} user${userIds.length !== 1 ? 's' : ''}.`;
    const modal = document.getElementById('notify-modal');
    modal.style.display = 'flex';
}

function closeNotifyModal() {
    document.getElementById('notify-modal').style.display = 'none';
}

async function submitNotification() {
    const title = document.getElementById('notify-title').value.trim();
    const message = document.getElementById('notify-message').value.trim();
    const statusEl = document.getElementById('notify-status');
    if (!title || !message) {
        statusEl.innerHTML = '<div class="alert alert-error">Title and message are required.</div>';
        return;
    }
    try {
        const res = await fetch(`${BASE_PATH}/dashboard/api/admin/notifications/send`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({user_ids: _notifyUserIds, title, message})
        });
        const data = await res.json();
        if (data.success) {
            statusEl.innerHTML = `<div class="alert alert-success">Sent to ${data.sent} user(s).</div>`;
            setTimeout(closeNotifyModal, 1500);
        } else {
            statusEl.innerHTML = `<div class="alert alert-error">${data.error || window.i18n.t('users.send_failed')}</div>`;
        }
    } catch (e) {
        statusEl.innerHTML = '<div class="alert alert-error">Network error.</div>';
    }
}

document.getElementById('notify-modal').addEventListener('click', function(e) {
    if (e.target === this) closeNotifyModal();
});

// Wire "Send Notification" bulk button
document.addEventListener('DOMContentLoaded', function() {
    const notifyBtn = document.getElementById('bulk-notify');
    if (notifyBtn) {
        notifyBtn.addEventListener('click', function() {
            const checked = Array.from(document.querySelectorAll('.user-checkbox:checked'))
                                 .map(cb => parseInt(cb.value));
            if (!checked.length) return;
            openNotifyModal(checked);
        });
    }
});
</script>
{% endblock %}
