<?php
if (!defined('ABSPATH')) {
    exit;
}

$ui_labels = isset($ui_labels) && is_array($ui_labels) ? $ui_labels : [];
$search = isset($search) ? eep_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 ? 'eep-user-management-shell space-y-4 md:space-y-6' : 'eep-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(
    'eep_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 = in_array($role, ['subscriber', 'event_submitter', 'administrator'], true) ? $role : 'subscriber';
    $role_label = $role === 'event_submitter'
        ? __('Event Submitter', 'nexdirectory')
        : ($role === 'administrator' ? __('Administrator', 'nexdirectory') : __('Subscriber', 'nexdirectory'));
    $verified = get_user_meta($user_id, 'eep_verified_organizer', true) === '1';
    $trusted_editor = $this->user_is_trusted_editor($user_id);
    $admin_note = eep_sanitize_textarea((string) get_user_meta($user_id, 'eep_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
        ? 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 = eep_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,
        '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('eep_manage_user_role_' . $user_id),
            'verified' => wp_create_nonce('eep_toggle_verified_' . $user_id),
            'trust' => wp_create_nonce('eep_toggle_user_edit_trust_' . $user_id),
            'event' => wp_create_nonce('eep_manage_user_event_' . $user_id),
            'note' => wp_create_nonce('eep_manage_user_note_' . $user_id),
        ],
    ];
}

$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 = '""';
}
?>

<style>
    [x-cloak] { display: none !important; }
    .custom-scrollbar::-webkit-scrollbar { height: 6px; width: 6px; }
    .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
    .hide-scroll::-webkit-scrollbar { display: none; }
    .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }
</style>

<script>
window.eepUserManagementPage = function(seedUsers, initialSearch, actionUrl) {
    const users = Array.isArray(seedUsers) ? seedUsers.map(function(user) {
        const row = Object.assign({}, user || {});
        row.events = Array.isArray(row.events) ? row.events : [];
        if (!row.selectedEventId && row.events.length > 0) {
            row.selectedEventId = row.events[0].id;
        }
        row.eventSubject = String(row.eventSubject || '');
        row.eventMessage = String(row.eventMessage || '');
        return row;
    }) : [];

    return {
        users: users,
        searchQuery: String(initialSearch || ''),
        actionUrl: String(actionUrl || ''),
        currentPage: 1,
        itemsPerPage: 100,
        toolsOpen: {},
        noteModal: {
            open: false,
            user: null
        },
        noteModalDraft: '',
        toast: { show: false, message: '', type: 'info', timeout: null },

        init() {
            this.$watch('searchQuery', () => {
                this.currentPage = 1;
            });
        },

        async postAction(fields) {
            if (!this.actionUrl) {
                throw new Error('Action endpoint is missing.');
            }
            const params = new URLSearchParams();
            params.append('eep_ajax', '1');
            params.append('redirect_to', window.location.href);

            (fields || []).forEach(function(field) {
                if (!field || typeof field.name !== 'string') {
                    return;
                }
                const rawValue = field.value;
                if (rawValue === null || rawValue === undefined) {
                    return;
                }
                params.append(field.name, String(rawValue));
            });

            const response = await fetch(this.actionUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: params.toString()
            });
            const text = await response.text();
            let payload = null;
            try {
                payload = text ? JSON.parse(text) : null;
            } catch (error) {
                payload = null;
            }

            if (!payload || payload.success !== true) {
                const message = payload && payload.data && payload.data.message
                    ? String(payload.data.message)
                    : 'Request failed.';
                throw new Error(message);
            }
            return payload.data || {};
        },

        updateUserEventCounters(user) {
            if (!user || !Array.isArray(user.events)) {
                return;
            }
            let published = 0;
            let pending = 0;
            let draft = 0;
            user.events.forEach(function(eventItem) {
                const status = String(eventItem && eventItem.status ? eventItem.status : '');
                if (status === 'publish') {
                    published += 1;
                } else if (status === 'pending') {
                    pending += 1;
                } else if (status === 'draft') {
                    draft += 1;
                }
            });
            user.eventsTotal = user.events.length;
            user.publishedEvents = published;
            user.pendingEvents = pending;
            user.draftEvents = draft;
        },

        updateUserRole(user, nextRole, selectEl) {
            if (!user || user.isAdmin) {
                return;
            }
            const role = String(nextRole || '');
            if (role !== 'subscriber' && role !== 'event_submitter') {
                if (selectEl) {
                    selectEl.value = String(user.role || 'subscriber');
                }
                return;
            }
            const previousRole = String(user.role || 'subscriber');
            if (role === previousRole) {
                return;
            }
            this.postAction([
                { name: 'action', value: 'eep_manage_user_role' },
                { name: 'user_id', value: user.id },
                { name: 'role', value: role },
                { name: 'eep_manage_user_nonce', value: user.nonces ? user.nonces.role : '' }
            ]).then((data) => {
                user.role = String(data.role || role);
                if (data.role_label) {
                    user.roleLabel = String(data.role_label);
                }
                this.showToast(String(data.message || 'User role updated.'), 'success');
            }).catch((error) => {
                user.role = previousRole;
                if (selectEl) {
                    selectEl.value = previousRole;
                }
                this.showToast(String(error && error.message ? error.message : 'Could not update role.'), 'error');
            });
        },

        toggleVerified(user) {
            if (!user || user.isAdmin) {
                return;
            }
            const nextVerified = !Boolean(user.verified);
            this.postAction([
                { name: 'action', value: 'eep_toggle_verified' },
                { name: 'user_id', value: user.id },
                { name: 'verified', value: nextVerified ? '1' : '0' },
                { name: 'eep_toggle_verified_nonce', value: user.nonces ? user.nonces.verified : '' }
            ]).then((data) => {
                user.verified = Boolean(data.verified);
                this.showToast(String(data.message || 'Verification updated.'), 'success');
            }).catch((error) => {
                this.showToast(String(error && error.message ? error.message : 'Could not update verification.'), 'error');
            });
        },

        updateUserTrust(user, nextState, selectEl) {
            if (!user || user.isAdmin) {
                return;
            }
            const requested = String(nextState || '');
            if (requested !== 'trusted' && requested !== 'require_approval') {
                if (selectEl) {
                    selectEl.value = String(user.trusted || 'require_approval');
                }
                return;
            }
            const previousState = String(user.trusted || 'require_approval');
            if (requested === previousState) {
                return;
            }
            this.postAction([
                { name: 'action', value: 'eep_toggle_user_edit_trust' },
                { name: 'user_id', value: user.id },
                { name: 'trusted', value: requested },
                { name: 'eep_toggle_user_edit_trust_nonce', value: user.nonces ? user.nonces.trust : '' }
            ]).then((data) => {
                user.trusted = String(data.trusted || requested);
                this.showToast(String(data.message || 'Trust settings updated.'), 'success');
            }).catch((error) => {
                user.trusted = previousState;
                if (selectEl) {
                    selectEl.value = previousState;
                }
                this.showToast(String(error && error.message ? error.message : 'Could not update trust settings.'), 'error');
            });
        },

        manageUserEvent(user, intent) {
            if (!user || !user.id || !user.selectedEventId) {
                this.showToast('Select an event first.', 'error');
                return;
            }
            const selectedId = Number(user.selectedEventId || 0);
            if (selectedId <= 0) {
                this.showToast('Select a valid event.', 'error');
                return;
            }

            this.postAction([
                { name: 'action', value: 'eep_manage_user_event' },
                { name: 'user_id', value: user.id },
                { name: 'event_id', value: selectedId },
                { name: 'intent', value: String(intent || '') },
                { name: 'admin_subject', value: String(user.eventSubject || '') },
                { name: 'admin_message', value: String(user.eventMessage || '') },
                { name: 'eep_manage_user_event_nonce', value: user.nonces ? user.nonces.event : '' }
            ]).then((data) => {
                if (data.intent === 'open_event' && data.open_url) {
                    window.open(String(data.open_url), '_blank', 'noopener,noreferrer');
                }
                if ((data.intent === 'publish_event' || data.intent === 'unpublish_event') && data.post_id) {
                    const eventId = Number(data.post_id || 0);
                    user.events.forEach(function(eventItem) {
                        if (Number(eventItem.id || 0) === eventId) {
                            eventItem.status = String(data.new_status || eventItem.status || '');
                            eventItem.status_label = String(data.status_label || eventItem.status_label || '');
                        }
                    });
                    this.updateUserEventCounters(user);
                }
                this.showToast(String(data.message || 'Event updated.'), 'success');
            }).catch((error) => {
                this.showToast(String(error && error.message ? error.message : 'Could not update event.'), 'error');
            });
        },

        get filteredUsers() {
            const query = String(this.searchQuery || '').trim().toLowerCase();
            if (query === '') {
                return this.users;
            }
            return this.users.filter((user) => {
                const name = String(user.name || '').toLowerCase();
                const email = String(user.email || '').toLowerCase();
                return name.indexOf(query) !== -1 || email.indexOf(query) !== -1;
            });
        },

        get paginatedUsers() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            return this.filteredUsers.slice(start, start + this.itemsPerPage);
        },

        get paginationStart() {
            return this.filteredUsers.length === 0 ? 0 : ((this.currentPage - 1) * this.itemsPerPage) + 1;
        },

        get paginationEnd() {
            return Math.min(this.currentPage * this.itemsPerPage, this.filteredUsers.length);
        },

        get totalPages() {
            return Math.max(1, Math.ceil(this.filteredUsers.length / this.itemsPerPage));
        },

        get verifiedCount() {
            return this.filteredUsers.filter((user) => !!user.verified).length;
        },

        get submitterCount() {
            return this.filteredUsers.filter((user) => String(user.role || '') === 'event_submitter').length;
        },

        get trustedCount() {
            return this.filteredUsers.filter((user) => String(user.trusted || '') === 'trusted').length;
        },

        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage += 1;
            }
        },

        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage -= 1;
            }
        },

        toggleTools(userId) {
            const key = String(userId || '');
            if (!key) {
                return;
            }
            this.toolsOpen[key] = !this.toolsOpen[key];
        },

        isToolsOpen(userId) {
            return !!this.toolsOpen[String(userId || '')];
        },

        loginAs(user) {
            if (!user || !user.urls || !user.urls.profile) {
                return;
            }
            this.showToast('Opening profile for ' + String(user.name || 'user') + '.', 'info');
            window.location.href = String(user.urls.profile);
        },

        openNotes(user) {
            if (!user || !user.id) {
                return;
            }
            this.noteModal.user = user;
            this.noteModalDraft = String(user.notes || '');
            this.noteModal.open = true;
            document.body.style.overflow = 'hidden';
        },

        closeNotes() {
            this.noteModal.open = false;
            this.noteModal.user = null;
            this.noteModalDraft = '';
            document.body.style.overflow = '';
        },

        saveNotes() {
            if (!this.noteModal.user || !this.noteModal.user.id) {
                return;
            }
            const modalUser = this.noteModal.user;
            const noteValue = String(this.noteModalDraft || '');
            this.postAction([
                { name: 'action', value: 'eep_manage_user_note' },
                { name: 'user_id', value: modalUser.id },
                { name: 'admin_note', value: noteValue },
                { name: 'eep_manage_user_note_nonce', value: modalUser.nonces ? modalUser.nonces.note : '' }
            ]).then((data) => {
                modalUser.notes = String(data.admin_note !== undefined ? data.admin_note : noteValue);
                this.closeNotes();
                this.showToast(String(data.message || 'Admin note saved.'), 'success');
            }).catch((error) => {
                this.showToast(String(error && error.message ? error.message : 'Could not save note.'), 'error');
            });
        },

        showToast(message, type) {
            this.toast.message = String(message || '');
            this.toast.type = String(type || 'info');
            this.toast.show = true;
            if (this.toast.timeout) {
                clearTimeout(this.toast.timeout);
            }
            this.toast.timeout = setTimeout(() => {
                this.toast.show = false;
            }, 2600);
        },

        exportCsv() {
            const headers = ['ID', 'Name', 'Email', 'Role', 'Verified', 'Trusted', 'Events', 'Pending', 'Last Active'];
            const rows = [headers.join(',')];
            this.filteredUsers.forEach((user) => {
                rows.push([
                    String(user.id || ''),
                    '"' + String(user.name || '').replace(/"/g, '""') + '"',
                    '"' + String(user.email || '').replace(/"/g, '""') + '"',
                    '"' + String(user.roleLabel || user.role || '').replace(/"/g, '""') + '"',
                    user.verified ? 'Yes' : 'No',
                    String(user.trusted || '') === 'trusted' ? 'Trusted' : 'Require Approval',
                    String(user.eventsTotal || 0),
                    String(user.pendingEvents || 0),
                    '"' + String(user.lastActive || '').replace(/"/g, '""') + '"'
                ].join(','));
            });

            const csv = rows.join('\n');
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'users_' + new Date().toISOString().slice(0, 10) + '.csv');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            this.showToast('CSV exported.', 'success');
        }
    };
};
</script>

<div class="eep-my-events eep-user-management bg-slate-50 text-slate-800 font-sans antialiased <?php echo esc_attr($root_padding_classes); ?>"
     x-data='eepUserManagementPage(<?php echo $managed_users_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, <?php echo $initial_search_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, <?php echo $action_url_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>)'
     x-cloak>

    <?php if (!$admin_context) : ?>
        <?php echo $this->render_notice(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
        <?php echo $this->render_platform_breadcrumbs(__('User Management', 'nexdirectory')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
    <?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>
                        <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>
                <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>
                <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">
                                    <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.isAdmin">
                                        <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.isAdmin">
                                        <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">
                                        <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>
                                        <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 $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'); ?>">
                                                <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">
                                                    <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>
                                                    <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>
                                                    <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>
                                                    <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">
                                            <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.isAdmin">
                                    <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.isAdmin">
                                    <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">
                                <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>
                                <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 $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'); ?>">
                                    <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">
                                        <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>
                                        <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>
                                        <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>
                                        <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">
                                <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>
