<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Templates use local variables supplied by the render context.
if (!defined('ABSPATH')) {
    exit;
}

$ui_labels = isset($ui_labels) && is_array($ui_labels) ? $ui_labels : [];
$search = isset($search) ? nexdirectory_sanitize_text((string) $search) : '';
$loaded_users = isset($users) && is_array($users) ? $users : [];
$singular_label = sanitize_text_field((string) ($ui_labels['singular'] ?? __('Event', 'nexdirectory')));
$plural_label = sanitize_text_field((string) ($ui_labels['plural'] ?? __('Events', 'nexdirectory')));
$owner_singular = sanitize_text_field((string) ($ui_labels['owner_singular'] ?? __('Organizer', 'nexdirectory')));
$owner_plural = sanitize_text_field((string) ($ui_labels['owner_plural'] ?? __('Organizers', 'nexdirectory')));
$singular_lower = sanitize_text_field((string) ($ui_labels['singular_lower'] ?? strtolower((string) $singular_label)));
$plural_lower = sanitize_text_field((string) ($ui_labels['plural_lower'] ?? strtolower((string) $plural_label)));
$page_kicker = sanitize_text_field((string) $this->get_event_hero_kicker_text());
$admin_context = !empty($admin_context);
$root_padding_classes = $admin_context ? 'pb-8 md:pb-8' : 'min-h-screen pb-24 md:pb-8';
$shell_classes = $admin_context ? 'nexdirectory-user-management-shell space-y-4 md:space-y-6' : 'nexdirectory-user-management-shell max-w-[1400px] mx-auto space-y-4 md:space-y-6 md:p-6';

$events_page_url = $this->get_platform_page_url(
    'nexdirectory_page_events_url',
    $this->get_profile_route_slugs('events'),
    $this->get_profile_route_default_url('events')
);
if (!is_string($events_page_url) || $events_page_url === '') {
    $events_page_url = home_url('/');
}

$managed_users_payload = [];
$stats_loaded = 0;
$stats_verified = 0;
$stats_submitters = 0;
$stats_trusted = 0;

foreach ($loaded_users as $managed_user) {
    if (!$managed_user instanceof WP_User) {
        continue;
    }

    $stats_loaded++;
    $user_id = (int) $managed_user->ID;
    $display_name = sanitize_text_field((string) ($managed_user->display_name ?: $managed_user->user_login));
    $email = sanitize_email((string) $managed_user->user_email);
    $roles = array_values(array_filter(array_map('sanitize_key', (array) $managed_user->roles)));
    $is_admin = in_array('administrator', $roles, true);
    $role = !empty($roles) ? (string) $roles[0] : 'subscriber';
    $role_mutable = in_array($role, ['subscriber', 'event_submitter'], true);
    $registered_roles = function_exists('wp_roles') ? (array) wp_roles()->roles : [];
    $registered_role_name = isset($registered_roles[$role]['name'])
        ? translate_user_role((string) $registered_roles[$role]['name'])
        : '';
    $role_label = $registered_role_name !== ''
        ? $registered_role_name
        : ucwords(str_replace('_', ' ', $role));
    $verified = get_user_meta($user_id, 'nexdirectory_verified_organizer', true) === '1';
    $trusted_editor = $this->user_is_trusted_editor($user_id);
    $admin_note = nexdirectory_sanitize_textarea((string) get_user_meta($user_id, 'nexdirectory_admin_user_note', true));
    $joined_ts = strtotime((string) $managed_user->user_registered);
    $joined_label = $joined_ts > 0 ? wp_date(get_option('date_format'), $joined_ts) : '';
    $last_active = $joined_ts > 0
        /* translators: %s: Placeholder value. */
        ? sprintf(__('Joined %s', 'nexdirectory'), $joined_label)
        : __('Recently', 'nexdirectory');

    if ($verified) {
        $stats_verified++;
    }
    if ($role === 'event_submitter') {
        $stats_submitters++;
    }
    if ($trusted_editor) {
        $stats_trusted++;
    }

    $events = method_exists($this, 'get_user_management_events')
        ? (array) $this->get_user_management_events($user_id, 14)
        : [];
    $status_counts = [
        'publish' => 0,
        'pending' => 0,
        'draft' => 0,
    ];
    $event_rows = [];
    foreach ($events as $event_post) {
        if (!$event_post instanceof WP_Post) {
            continue;
        }
        $event_id = (int) $event_post->ID;
        if ($event_id <= 0) {
            continue;
        }
        $status = sanitize_key((string) get_post_status($event_id));
        if (isset($status_counts[$status])) {
            $status_counts[$status]++;
        }
        $event_rows[] = [
            'id' => $event_id,
            'title' => sanitize_text_field((string) get_the_title($event_id)),
            'status' => $status,
            'status_label' => ucfirst($status),
        ];
    }

    $user_events_url = nexdirectory_add_query_arg('organizer', $user_id, $events_page_url);
    $initial = mb_substr($display_name, 0, 1);
    if (!is_string($initial) || $initial === '') {
        $initial = 'U';
    }

    $managed_users_payload[] = [
        'id' => $user_id,
        'name' => $display_name,
        'email' => $email,
        'initial' => strtoupper((string) $initial),
        'role' => $role,
        'roleLabel' => sanitize_text_field((string) $role_label),
        'isAdmin' => $is_admin,
        'roleMutable' => $role_mutable,
        'verified' => $verified,
        'trusted' => $trusted_editor ? 'trusted' : 'require_approval',
        'lastActive' => $last_active,
        'notes' => $admin_note,
        'eventsTotal' => count($event_rows),
        'pendingEvents' => (int) $status_counts['pending'],
        'publishedEvents' => (int) $status_counts['publish'],
        'draftEvents' => (int) $status_counts['draft'],
        'events' => $event_rows,
        'selectedEventId' => isset($event_rows[0]['id']) ? (int) $event_rows[0]['id'] : 0,
        'urls' => [
            'profile' => esc_url_raw(admin_url('user-edit.php?user_id=' . $user_id)),
            'events' => esc_url_raw((string) $user_events_url),
        ],
        'nonces' => [
            'role' => wp_create_nonce('nexdirectory_manage_user_role'),
            'verified' => wp_create_nonce('nexdirectory_toggle_verified'),
            'trust' => wp_create_nonce('nexdirectory_toggle_user_edit_trust'),
            'event' => wp_create_nonce('nexdirectory_manage_user_event'),
            'note' => wp_create_nonce('nexdirectory_manage_user_note'),
        ],
    ];
}

$json_flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
    $json_flags |= JSON_INVALID_UTF8_SUBSTITUTE;
}
$managed_users_json = wp_json_encode($managed_users_payload, $json_flags);
if (!is_string($managed_users_json) || $managed_users_json === '') {
    $managed_users_json = '[]';
}
$initial_search_json = wp_json_encode((string) $search, $json_flags);
if (!is_string($initial_search_json) || $initial_search_json === '') {
    $initial_search_json = '""';
}
$action_url = esc_url(admin_url('admin-post.php'));
$action_url_json = wp_json_encode((string) admin_url('admin-post.php'), $json_flags);
if (!is_string($action_url_json) || $action_url_json === '') {
    $action_url_json = '""';
}
?>

<?php $this->enqueue_local_style_asset('templates-frontend-user-management-php-style-1', 'assets/generated/templates-frontend-user-management-php-style-1.css'); ?>

<?php $this->enqueue_local_script_asset('templates-frontend-user-management-php-script-1', 'assets/generated/templates-frontend-user-management-php-script-1.js'); ?>

<div class="nexdirectory-my-events nexdirectory-user-management bg-slate-50 text-slate-800 font-sans antialiased <?php echo esc_attr($root_padding_classes); ?>"
     x-data='nexdirectoryUserManagementPage(<?php echo esc_attr((string) $managed_users_json); ?>, <?php echo esc_attr((string) $initial_search_json); ?>, <?php echo esc_attr((string) $action_url_json); ?>)'
     x-cloak>

    <?php if (!$admin_context) : ?>
        <?php echo wp_kses((string) $this->render_notice(), NEXDIRECTORY_Escaping::allowed_html()); ?>
        <?php
        $nexdirectory_breadcrumb_markup = NEXDIRECTORY_Escaping::prepare_markup_for_wp_kses((string) $this->render_platform_breadcrumbs(__('User Management', 'nexdirectory')));
        echo wp_kses($nexdirectory_breadcrumb_markup, NEXDIRECTORY_Escaping::allowed_html($nexdirectory_breadcrumb_markup));
        ?>
    <?php endif; ?>

    <div class="<?php echo esc_attr($shell_classes); ?>">

        <?php if (!$admin_context) : ?>
            <header class="bg-white md:rounded-2xl shadow-sm p-5 md:p-8 border border-slate-200 relative overflow-hidden">
                <div class="absolute -top-24 -right-24 w-64 h-64 bg-indigo-50 rounded-full blur-3xl opacity-60 pointer-events-none hidden md:block"></div>
                <div class="flex justify-between items-start">
                    <div>
                        <span class="inline-block py-1 px-2.5 rounded-md bg-indigo-100 text-indigo-700 text-[10px] font-bold tracking-wider uppercase mb-2"><?php echo esc_html($page_kicker); ?></span>
                        <h1 class="text-2xl md:text-3xl font-extrabold text-slate-900 mb-1 md:mb-2 tracking-tight"><?php esc_html_e('User Management', 'nexdirectory'); ?></h1>
                        <?php /* translators: 1: Placeholder value 1, 2: Placeholder value 2. */ ?>
                        <p class="text-sm md:text-base text-slate-500 max-w-2xl leading-relaxed"><?php echo esc_html(sprintf(__('Adjust roles, verify %1$s, and monitor %2$s activity.', 'nexdirectory'), strtolower((string) $owner_plural), strtolower((string) $plural_label))); ?></p>
                    </div>
                </div>
            </header>
        <?php endif; ?>

        <section class="flex overflow-x-auto hide-scroll gap-3 md:grid md:grid-cols-4 md:gap-4 snap-x snap-mandatory">
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 flex items-center space-x-3 min-w-[200px] md:min-w-0 snap-center shrink-0">
                <div class="p-2.5 bg-blue-50 text-blue-600 rounded-lg"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"></path></svg></div>
                <div><p class="text-xs font-semibold text-slate-500 uppercase tracking-wide"><?php esc_html_e('Loaded Users', 'nexdirectory'); ?></p><p class="text-xl font-bold text-slate-900" x-text="filteredUsers.length"></p></div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 flex items-center space-x-3 min-w-[200px] md:min-w-0 snap-center shrink-0">
                <div class="p-2.5 bg-emerald-50 text-emerald-600 rounded-lg"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg></div>
                <?php /* translators: %s: Placeholder value. */ ?>
                <div><p class="text-xs font-semibold text-slate-500 uppercase tracking-wide"><?php echo esc_html(sprintf(__('Verified %s', 'nexdirectory'), $owner_plural)); ?></p><p class="text-xl font-bold text-slate-900" x-text="verifiedCount"></p></div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 flex items-center space-x-3 min-w-[200px] md:min-w-0 snap-center shrink-0">
                <div class="p-2.5 bg-purple-50 text-purple-600 rounded-lg"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg></div>
                <?php /* translators: %s: Placeholder value. */ ?>
                <div><p class="text-xs font-semibold text-slate-500 uppercase tracking-wide"><?php echo esc_html(sprintf(__('%s Submitters', 'nexdirectory'), $singular_label)); ?></p><p class="text-xl font-bold text-slate-900" x-text="submitterCount"></p></div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 flex items-center space-x-3 min-w-[200px] md:min-w-0 snap-center shrink-0">
                <div class="p-2.5 bg-amber-50 text-amber-600 rounded-lg"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></div>
                <div><p class="text-xs font-semibold text-slate-500 uppercase tracking-wide"><?php esc_html_e('Trusted Editors', 'nexdirectory'); ?></p><p class="text-xl font-bold text-slate-900" x-text="trustedCount"></p></div>
            </div>
        </section>

        <section class="bg-white md:rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
            <div class="p-4 md:p-6 border-b border-slate-200 bg-slate-50/80 flex flex-col md:flex-row md:items-center justify-between gap-3">
                <div class="hidden md:block">
                    <h2 class="text-lg font-bold text-slate-900"><?php esc_html_e('Managed Accounts', 'nexdirectory'); ?></h2>
                </div>

                <div class="flex flex-col sm:flex-row gap-2 w-full md:w-auto">
                    <div class="relative w-full md:w-72">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-5.2-5.2M10.8 18a7.2 7.2 0 100-14.4 7.2 7.2 0 000 14.4z"></path></svg>
                        </div>
                        <input type="text" x-model="searchQuery" class="block w-full pl-9 pr-3 py-2.5 md:py-2 border border-slate-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-indigo-500 outline-none" placeholder="<?php esc_attr_e('Search users...', 'nexdirectory'); ?>">
                    </div>

                    <div class="flex gap-2 w-full md:w-auto">
                        <button type="button" @click="exportCsv()" class="flex-1 md:flex-none inline-flex items-center justify-center px-3 py-2.5 md:py-2 border border-slate-300 shadow-sm text-sm font-medium rounded-lg text-slate-700 bg-white active:bg-slate-50">
                            <svg class="w-4 h-4 mr-2 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 16v-8m0 8l-3-3m3 3l3-3M4 20h16"></path></svg>
                            <?php esc_html_e('Export CSV', 'nexdirectory'); ?>
                        </button>

                        <div x-data="{ open: false }" class="relative flex-1 md:flex-none">
                            <button type="button" @click="open = !open" @click.outside="open = false" class="w-full inline-flex items-center justify-center px-3 py-2.5 md:py-2 border border-slate-300 shadow-sm text-sm font-medium rounded-lg text-slate-700 bg-white active:bg-slate-50">
                                <svg class="w-4 h-4 md:mr-2 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 100 20 10 10 0 000-20z"></path></svg>
                                <span class="hidden md:inline"><?php esc_html_e('Action Key', 'nexdirectory'); ?></span>
                            </button>
                            <div x-show="open" x-transition class="absolute right-0 mt-2 w-64 rounded-xl shadow-lg bg-white border border-slate-200 ring-1 ring-black ring-opacity-5 z-20 p-4">
                                <h4 class="text-xs font-bold text-slate-800 uppercase tracking-wider mb-2"><?php esc_html_e('Icon Legend', 'nexdirectory'); ?></h4>
                                <ul class="text-xs text-slate-600 space-y-3">
                                    <?php /* translators: %s: Placeholder value. */ ?>
                                    <li><span class="inline-flex w-4 h-4 mr-2 align-middle items-center justify-center"><svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg></span><?php echo esc_html(sprintf(__('View %s', 'nexdirectory'), $plural_label)); ?></li>
                                    <li><span class="inline-flex w-4 h-4 mr-2 align-middle items-center justify-center"><svg class="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg></span><?php esc_html_e('Internal admin note', 'nexdirectory'); ?></li>
                                    <li><span class="inline-flex w-4 h-4 mr-2 align-middle items-center justify-center"><svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></span><?php esc_html_e('Open profile', 'nexdirectory'); ?></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="hidden md:block overflow-x-auto custom-scrollbar">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-wider"><?php esc_html_e('User', 'nexdirectory'); ?></th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-wider"><?php esc_html_e('Role Setup', 'nexdirectory'); ?></th>
                            <th class="px-6 py-4 text-center text-xs font-bold text-slate-500 uppercase tracking-wider"><?php esc_html_e('Verification', 'nexdirectory'); ?></th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-wider"><?php esc_html_e('Edit Permissions', 'nexdirectory'); ?></th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-500 uppercase tracking-wider"><?php echo esc_html($plural_label); ?></th>
                            <th class="px-6 py-4 text-right text-xs font-bold text-slate-500 uppercase tracking-wider"><?php esc_html_e('Quick Actions', 'nexdirectory'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-slate-100">
                        <tr x-show="paginatedUsers.length === 0">
                            <td colspan="6" class="px-6 py-12 text-center text-slate-500 font-medium"><?php esc_html_e('No users found.', 'nexdirectory'); ?></td>
                        </tr>
                        <template x-for="user in paginatedUsers" :key="'desktop-' + user.id">
                            <tr class="hover:bg-slate-50/50">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold text-lg border border-indigo-200" x-text="user.initial"></div>
                                        <div class="ml-4">
                                            <div class="text-sm font-bold text-slate-900" x-text="user.name"></div>
                                            <div class="text-xs text-slate-500 mt-0.5" x-text="user.email"></div>
                                            <div class="text-[10px] text-slate-400 mt-0.5" x-text="user.lastActive"></div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <template x-if="user.roleMutable">
                                        <select :value="user.role" @change="updateUserRole(user, $event.target.value, $event.target)" class="block w-full pl-3 pr-8 py-1.5 text-sm border-slate-300 rounded-lg bg-slate-50 border outline-none focus:ring-1 focus:ring-indigo-500">
                                            <option value="subscriber"><?php esc_html_e('Subscriber', 'nexdirectory'); ?></option>
                                            <option value="event_submitter"><?php esc_html_e('Event Submitter', 'nexdirectory'); ?></option>
                                        </select>
                                    </template>
                                    <template x-if="!user.roleMutable">
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold border bg-slate-100 text-slate-700 border-slate-200"><?php esc_html_e('Administrator', 'nexdirectory'); ?></span>
                                    </template>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-center">
                                    <template x-if="!user.isAdmin">
                                        <button type="button" @click="toggleVerified(user)" class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold border outline-none" :class="user.verified ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-slate-50 text-slate-500 border-slate-200'">
                                            <span x-text="user.verified ? '<?php echo esc_js(__('Verified', 'nexdirectory')); ?>' : '<?php echo esc_js(__('Unverified', 'nexdirectory')); ?>'"></span>
                                        </button>
                                    </template>
                                    <template x-if="user.isAdmin">
                                        <span class="text-xs text-slate-400"><?php esc_html_e('N/A', 'nexdirectory'); ?></span>
                                    </template>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <template x-if="!user.isAdmin">
                                        <select :value="user.trusted" @change="updateUserTrust(user, $event.target.value, $event.target)" class="block w-full pl-3 pr-8 py-1.5 text-sm border-slate-300 rounded-lg bg-slate-50 border outline-none focus:ring-1 focus:ring-indigo-500">
                                            <option value="require_approval"><?php esc_html_e('Require Approval', 'nexdirectory'); ?></option>
                                            <option value="trusted"><?php esc_html_e('Trust Edits', 'nexdirectory'); ?></option>
                                        </select>
                                    </template>
                                    <template x-if="user.isAdmin">
                                        <span class="text-xs text-slate-400"><?php esc_html_e('Always trusted', 'nexdirectory'); ?></span>
                                    </template>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap flex items-center gap-2">
                                    <span class="bg-slate-100 text-slate-700 py-1 px-3 rounded-md border border-slate-200 text-sm font-semibold" x-text="user.eventsTotal"></span>
                                    <span x-show="user.pendingEvents > 0" class="inline-flex bg-rose-100 text-rose-700 border border-rose-200 rounded-full px-2 py-0.5 text-xs font-bold">
                                        <span x-text="user.pendingEvents"></span><span class="ml-1 text-[10px] uppercase"><?php esc_html_e('Pending', 'nexdirectory'); ?></span>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right">
                                    <div class="flex justify-end space-x-2">
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <a :href="user.urls.events" class="w-8 h-8 rounded-lg bg-white border border-slate-200 text-slate-500 hover:text-indigo-600 inline-flex items-center justify-center" title="<?php echo esc_attr(sprintf(__('View %s', 'nexdirectory'), $plural_label)); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                                        </a>
                                        <button type="button" @click="loginAs(user)" class="w-8 h-8 rounded-lg bg-white border border-slate-200 text-slate-500 hover:text-indigo-600 inline-flex items-center justify-center" title="<?php esc_attr_e('Login As User (opens profile)', 'nexdirectory'); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path></svg>
                                        </button>
                                        <button type="button" @click="openNotes(user)" class="w-8 h-8 rounded-lg bg-white border inline-flex items-center justify-center" :class="user.notes ? 'text-amber-500 bg-amber-50 border-amber-200' : 'text-slate-500 border-slate-200 hover:text-amber-500'" title="<?php esc_attr_e('Internal Admin Note', 'nexdirectory'); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h8m-8 4h6m5 2H6a2 2 0 01-2-2V6a2 2 0 012-2h8l6 6v8a2 2 0 01-2 2z"></path></svg>
                                        </button>
                                        <a :href="user.urls.profile" class="w-8 h-8 rounded-lg bg-white border border-slate-200 text-slate-500 hover:text-indigo-600 inline-flex items-center justify-center" title="<?php esc_attr_e('Open Profile', 'nexdirectory'); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        </a>
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <button type="button" @click="toggleTools(user.id)" class="w-8 h-8 rounded-lg bg-white border border-slate-200 text-slate-500 hover:text-indigo-600 inline-flex items-center justify-center" title="<?php echo esc_attr(sprintf(__('Manage %s', 'nexdirectory'), $plural_label)); ?>">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                                        </button>
                                    </div>
                                    <div x-show="isToolsOpen(user.id)" x-cloak class="mt-3 text-left">
                                        <template x-if="user.events.length > 0">
                                            <form method="post" action="<?php echo esc_url($action_url); ?>" @submit.prevent class="border border-slate-200 rounded-lg p-3 bg-slate-50 space-y-2">
                                                <select x-model="user.selectedEventId" class="w-full h-9 px-2 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500">
                                                    <template x-for="eventItem in user.events" :key="'event-' + user.id + '-' + eventItem.id">
                                                        <option :value="eventItem.id" x-text="eventItem.title + ' (' + eventItem.status_label + ')'"></option>
                                                    </template>
                                                </select>
                                                <input type="text" x-model="user.eventSubject" class="w-full h-9 px-2 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500" placeholder="<?php esc_attr_e('Email subject (optional)', 'nexdirectory'); ?>">
                                                <?php /* translators: %s: Placeholder value. */ ?>
                                                <textarea x-model="user.eventMessage" rows="2" class="w-full px-2 py-1.5 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500" placeholder="<?php echo esc_attr(sprintf(__('Email note to %s owner (optional)', 'nexdirectory'), $singular_lower)); ?>"></textarea>
                                                <div class="grid grid-cols-2 gap-2">
                                                    <?php /* translators: %s: Placeholder value. */ ?>
                                                    <button type="button" @click="manageUserEvent(user, 'open_event')" class="px-2 py-2 text-xs rounded-md border border-slate-300 bg-white text-slate-700"><?php echo esc_html(sprintf(__('Open %s', 'nexdirectory'), $singular_label)); ?></button>
                                                    <?php /* translators: %s: Placeholder value. */ ?>
                                                    <button type="button" @click="manageUserEvent(user, 'publish_event')" class="px-2 py-2 text-xs rounded-md border border-emerald-200 bg-emerald-50 text-emerald-700"><?php echo esc_html(sprintf(__('Publish %s', 'nexdirectory'), $singular_label)); ?></button>
                                                    <?php /* translators: %s: Placeholder value. */ ?>
                                                    <button type="button" @click="manageUserEvent(user, 'unpublish_event')" class="px-2 py-2 text-xs rounded-md border border-amber-200 bg-amber-50 text-amber-700"><?php echo esc_html(sprintf(__('Unpublish %s', 'nexdirectory'), $singular_label)); ?></button>
                                                    <?php /* translators: %s: Placeholder value. */ ?>
                                                    <button type="button" @click="manageUserEvent(user, 'email_owner')" class="px-2 py-2 text-xs rounded-md border border-indigo-200 bg-indigo-50 text-indigo-700"><?php echo esc_html(sprintf(__('Email %s', 'nexdirectory'), $owner_singular)); ?></button>
                                                </div>
                                            </form>
                                        </template>
                                        <template x-if="user.events.length === 0">
                                            <?php /* translators: %s: Placeholder value. */ ?>
                                            <p class="text-xs text-slate-500"><?php echo esc_html(sprintf(__('No %s available for this user.', 'nexdirectory'), strtolower((string) $plural_label))); ?></p>
                                        </template>
                                    </div>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>

            <div class="md:hidden bg-slate-50/50 p-3 space-y-3">
                <div x-show="paginatedUsers.length === 0" class="py-10 text-center text-slate-500 text-sm"><?php esc_html_e('No users found.', 'nexdirectory'); ?></div>
                <template x-for="user in paginatedUsers" :key="'mobile-' + user.id">
                    <div class="bg-white border border-slate-200 rounded-xl p-4 shadow-sm">
                        <div class="flex justify-between items-start mb-4">
                            <div class="flex items-center space-x-3">
                                <div class="h-10 w-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold text-lg border border-indigo-200" x-text="user.initial"></div>
                                <div>
                                    <div class="font-bold text-slate-900 leading-tight" x-text="user.name"></div>
                                    <div class="text-xs text-slate-500" x-text="user.email"></div>
                                    <div class="text-[10px] text-slate-400 mt-0.5" x-text="user.lastActive"></div>
                                </div>
                            </div>
                            <template x-if="!user.isAdmin">
                                <button type="button" @click="toggleVerified(user)" class="text-xs px-2 py-1 rounded-full border" :class="user.verified ? 'text-emerald-700 bg-emerald-50 border-emerald-200' : 'text-slate-500 bg-slate-50 border-slate-200'" x-text="user.verified ? '<?php echo esc_js(__('Verified', 'nexdirectory')); ?>' : '<?php echo esc_js(__('Unverified', 'nexdirectory')); ?>'"></button>
                            </template>
                        </div>

                        <div class="grid grid-cols-1 gap-3 mb-4">
                            <div>
                                <label class="text-[10px] font-bold text-slate-500 uppercase mb-1 block"><?php esc_html_e('Role', 'nexdirectory'); ?></label>
                                <template x-if="user.roleMutable">
                                    <select :value="user.role" @change="updateUserRole(user, $event.target.value, $event.target)" class="w-full h-10 px-2 text-sm border-slate-200 rounded-lg bg-slate-50 border outline-none focus:ring-1 focus:ring-indigo-500">
                                        <option value="subscriber"><?php esc_html_e('Subscriber', 'nexdirectory'); ?></option>
                                        <option value="event_submitter"><?php esc_html_e('Event Submitter', 'nexdirectory'); ?></option>
                                    </select>
                                </template>
                                <template x-if="!user.roleMutable">
                                    <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold border bg-slate-100 text-slate-700 border-slate-200"><?php esc_html_e('Administrator', 'nexdirectory'); ?></span>
                                </template>
                            </div>
                            <div>
                                <label class="text-[10px] font-bold text-slate-500 uppercase mb-1 block"><?php esc_html_e('Trust Edits', 'nexdirectory'); ?></label>
                                <template x-if="!user.isAdmin">
                                    <select :value="user.trusted" @change="updateUserTrust(user, $event.target.value, $event.target)" class="w-full h-10 px-2 text-sm border-slate-200 rounded-lg bg-slate-50 border outline-none focus:ring-1 focus:ring-indigo-500">
                                        <option value="require_approval"><?php esc_html_e('Require Approval', 'nexdirectory'); ?></option>
                                        <option value="trusted"><?php esc_html_e('Trust Edits', 'nexdirectory'); ?></option>
                                    </select>
                                </template>
                                <template x-if="user.isAdmin">
                                    <span class="text-xs text-slate-400"><?php esc_html_e('Always trusted', 'nexdirectory'); ?></span>
                                </template>
                            </div>
                        </div>

                        <div class="flex justify-between items-center pt-3 border-t border-slate-100">
                            <div class="flex items-center gap-2">
                                <span class="bg-slate-100 text-slate-700 py-1 px-2.5 rounded text-xs font-bold border border-slate-200" x-text="user.eventsTotal + ' <?php echo esc_js($plural_label); ?>'"></span>
                                <span x-show="user.pendingEvents > 0" class="inline-flex bg-rose-100 text-rose-700 border border-rose-200 rounded px-1.5 py-0.5 text-[10px] font-bold"><span x-text="user.pendingEvents"></span> <?php esc_html_e('Pending', 'nexdirectory'); ?></span>
                            </div>
                            <div class="flex space-x-1">
                                <?php /* translators: %s: Placeholder value. */ ?>
                                <a :href="user.urls.events" class="h-8 w-8 rounded bg-slate-50 flex items-center justify-center border border-slate-200 text-slate-500 active:bg-slate-100" title="<?php echo esc_attr(sprintf(__('View %s', 'nexdirectory'), $plural_label)); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg></a>
                                <button type="button" @click="openNotes(user)" class="h-8 w-8 rounded bg-slate-50 flex items-center justify-center border active:bg-slate-100" :class="user.notes ? 'text-amber-500 border-amber-200 bg-amber-50' : 'text-slate-500 border-slate-200'" title="<?php esc_attr_e('Internal Admin Note', 'nexdirectory'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h8m-8 4h6m5 2H6a2 2 0 01-2-2V6a2 2 0 012-2h8l6 6v8a2 2 0 01-2 2z"></path></svg></button>
                                <button type="button" @click="loginAs(user)" class="h-8 w-8 rounded bg-slate-50 flex items-center justify-center border border-slate-200 text-slate-500 active:bg-slate-100" title="<?php esc_attr_e('Login As User (opens profile)', 'nexdirectory'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path></svg></button>
                                <a :href="user.urls.profile" class="h-8 w-8 rounded bg-slate-50 flex items-center justify-center border border-slate-200 text-slate-500 active:bg-slate-100" title="<?php esc_attr_e('Open Profile', 'nexdirectory'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></a>
                                <?php /* translators: %s: Placeholder value. */ ?>
                                <button type="button" @click="toggleTools(user.id)" class="h-8 w-8 rounded bg-slate-50 flex items-center justify-center border border-slate-200 text-slate-500 active:bg-slate-100" title="<?php echo esc_attr(sprintf(__('Manage %s', 'nexdirectory'), $plural_label)); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg></button>
                            </div>
                        </div>

                        <div x-show="isToolsOpen(user.id)" x-cloak class="mt-3">
                            <template x-if="user.events.length > 0">
                                <form method="post" action="<?php echo esc_url($action_url); ?>" @submit.prevent class="border border-slate-200 rounded-lg p-3 bg-slate-50 space-y-2">
                                    <select x-model="user.selectedEventId" class="w-full h-9 px-2 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500">
                                        <template x-for="eventItem in user.events" :key="'event-mobile-' + user.id + '-' + eventItem.id">
                                            <option :value="eventItem.id" x-text="eventItem.title + ' (' + eventItem.status_label + ')'"></option>
                                        </template>
                                    </select>
                                    <input type="text" x-model="user.eventSubject" class="w-full h-9 px-2 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500" placeholder="<?php esc_attr_e('Email subject (optional)', 'nexdirectory'); ?>">
                                    <?php /* translators: %s: Placeholder value. */ ?>
                                    <textarea x-model="user.eventMessage" rows="2" class="w-full px-2 py-1.5 text-xs border-slate-200 rounded-md bg-white border outline-none focus:ring-1 focus:ring-indigo-500" placeholder="<?php echo esc_attr(sprintf(__('Email note to %s owner (optional)', 'nexdirectory'), $singular_lower)); ?>"></textarea>
                                    <div class="grid grid-cols-2 gap-2">
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <button type="button" @click="manageUserEvent(user, 'open_event')" class="px-2 py-2 text-xs rounded-md border border-slate-300 bg-white text-slate-700"><?php echo esc_html(sprintf(__('Open %s', 'nexdirectory'), $singular_label)); ?></button>
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <button type="button" @click="manageUserEvent(user, 'publish_event')" class="px-2 py-2 text-xs rounded-md border border-emerald-200 bg-emerald-50 text-emerald-700"><?php echo esc_html(sprintf(__('Publish %s', 'nexdirectory'), $singular_label)); ?></button>
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <button type="button" @click="manageUserEvent(user, 'unpublish_event')" class="px-2 py-2 text-xs rounded-md border border-amber-200 bg-amber-50 text-amber-700"><?php echo esc_html(sprintf(__('Unpublish %s', 'nexdirectory'), $singular_label)); ?></button>
                                        <?php /* translators: %s: Placeholder value. */ ?>
                                        <button type="button" @click="manageUserEvent(user, 'email_owner')" class="px-2 py-2 text-xs rounded-md border border-indigo-200 bg-indigo-50 text-indigo-700"><?php echo esc_html(sprintf(__('Email %s', 'nexdirectory'), $owner_singular)); ?></button>
                                    </div>
                                </form>
                            </template>
                            <template x-if="user.events.length === 0">
                                <?php /* translators: %s: Placeholder value. */ ?>
                                <p class="text-xs text-slate-500"><?php echo esc_html(sprintf(__('No %s available for this user.', 'nexdirectory'), strtolower((string) $plural_label))); ?></p>
                            </template>
                        </div>
                    </div>
                </template>
            </div>

            <div class="bg-white px-4 md:px-6 py-4 border-t border-slate-200">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div class="flex justify-between items-center text-sm text-slate-600">
                        <div class="md:hidden font-bold"><?php esc_html_e('Page', 'nexdirectory'); ?> <span x-text="currentPage"></span> / <span x-text="totalPages"></span></div>
                        <div class="hidden md:block">
                            <?php esc_html_e('Showing', 'nexdirectory'); ?> <span class="font-bold" x-text="paginationStart"></span> <?php esc_html_e('to', 'nexdirectory'); ?> <span class="font-bold" x-text="paginationEnd"></span> <?php esc_html_e('of', 'nexdirectory'); ?> <span class="font-bold" x-text="filteredUsers.length"></span>
                        </div>
                        <div class="flex items-center gap-2 md:hidden">
                            <label class="text-xs"><?php esc_html_e('Per Page', 'nexdirectory'); ?>:</label>
                            <select x-model.number="itemsPerPage" @change="currentPage = 1" class="text-xs py-1 border-slate-300 rounded">
                                <option value="25">25</option><option value="50">50</option><option value="100">100</option>
                            </select>
                        </div>
                    </div>

                    <div class="hidden md:flex items-center gap-2">
                        <span class="text-sm text-slate-500"><?php esc_html_e('Rows per page:', 'nexdirectory'); ?></span>
                        <select x-model.number="itemsPerPage" @change="currentPage = 1" class="text-sm py-1.5 border-slate-300 rounded-md">
                            <option value="25">25</option><option value="50">50</option><option value="100">100</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-2 md:flex gap-2">
                        <button type="button" @click="prevPage()" :disabled="currentPage === 1" class="w-full md:w-auto px-4 py-3 md:py-2 border border-slate-300 rounded-lg bg-white text-sm font-bold text-slate-700 disabled:opacity-50 active:bg-slate-50">
                            <?php esc_html_e('Prev', 'nexdirectory'); ?>
                        </button>
                        <button type="button" @click="nextPage()" :disabled="currentPage === totalPages" class="w-full md:w-auto px-4 py-3 md:py-2 border border-slate-300 rounded-lg bg-white text-sm font-bold text-slate-700 disabled:opacity-50 active:bg-slate-50">
                            <?php esc_html_e('Next', 'nexdirectory'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </section>

        <div x-show="noteModal.open" x-cloak class="fixed inset-0 z-50 flex items-end md:items-center justify-center p-4 sm:p-0">
            <div class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm" @click="closeNotes()"></div>

            <div x-show="noteModal.open" x-transition class="relative bg-white rounded-2xl w-full max-w-lg overflow-hidden shadow-2xl">
                <div class="w-12 h-1.5 bg-slate-200 rounded-full mx-auto mt-3 md:hidden"></div>
                <div class="p-5">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-bold text-slate-900">
                            <?php esc_html_e('Notes:', 'nexdirectory'); ?>
                            <span class="text-indigo-600" x-text="noteModal.user ? noteModal.user.name : ''"></span>
                        </h3>
                        <button type="button" @click="closeNotes()" class="text-slate-400 p-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>
                    </div>
                    <p class="text-xs text-slate-500 mb-3"><?php esc_html_e('Internal admin notes only.', 'nexdirectory'); ?></p>
                    <textarea name="admin_note" x-model="noteModalDraft" rows="4" class="w-full border-slate-300 rounded-xl p-3 bg-slate-50 outline-none focus:ring-2 focus:ring-indigo-500 text-sm mb-4" placeholder="<?php esc_attr_e('Write a note...', 'nexdirectory'); ?>"></textarea>

                    <div class="grid grid-cols-2 gap-2">
                        <button type="button" @click="closeNotes()" class="w-full py-3 rounded-xl border border-slate-300 text-slate-700 font-semibold active:bg-slate-50">
                            <?php esc_html_e('Cancel', 'nexdirectory'); ?>
                        </button>
                        <button type="button" @click="saveNotes()" class="w-full py-3 bg-indigo-600 rounded-xl text-white font-bold active:bg-indigo-700">
                            <?php esc_html_e('Save Note', 'nexdirectory'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="fixed top-4 left-4 right-4 md:top-auto md:left-auto md:bottom-5 md:right-5 z-50 pointer-events-none">
            <div x-show="toast.show" x-transition.opacity class="max-w-sm w-full mx-auto md:ml-auto bg-slate-900 text-white shadow-xl rounded-xl p-4 flex items-center pointer-events-auto">
                <p class="text-sm font-medium flex-1" x-text="toast.message"></p>
                <button type="button" @click="toast.show = false" class="text-slate-400 p-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
        </div>
    </div>
</div>
