let allUsers = [];
let allRoles = [];
let permissionCatalog = [];
let editingUserId = null;

const PHONE_COUNTRIES = [
  {name:'Lebanon', code:'+961', flag:'🇱🇧'},
  {name:'United Arab Emirates', code:'+971', flag:'🇦🇪'},
  {name:'Saudi Arabia', code:'+966', flag:'🇸🇦'},
  {name:'Qatar', code:'+974', flag:'🇶🇦'},
  {name:'Kuwait', code:'+965', flag:'🇰🇼'},
  {name:'Bahrain', code:'+973', flag:'🇧🇭'},
  {name:'Oman', code:'+968', flag:'🇴🇲'},
  {name:'Jordan', code:'+962', flag:'🇯🇴'},
  {name:'Egypt', code:'+20', flag:'🇪🇬'},
  {name:'Turkey', code:'+90', flag:'🇹🇷'},
  {name:'United States', code:'+1', flag:'🇺🇸'},
  {name:'Canada', code:'+1', flag:'🇨🇦'},
  {name:'United Kingdom', code:'+44', flag:'🇬🇧'},
  {name:'France', code:'+33', flag:'🇫🇷'},
  {name:'Germany', code:'+49', flag:'🇩🇪'},
  {name:'Australia', code:'+61', flag:'🇦🇺'}
];

if (typeof Pyrk.formatDateTime !== 'function') {
  Pyrk.formatDateTime = value => {
    if (!value) return '—';
    const s = String(value).trim().replace('T', ' ');
    const m = s.match(/^(\d{4})-(\d{2})-(\d{2})/);
    const date = m ? `${m[3]}/${m[2]}/${m[1]}` : s.slice(0, 10);
    const time = s.length >= 16 ? s.slice(11, 16) : '';
    return time ? `${date} ${time}` : date;
  };
}

function countryLabel(country) {
  return `${country.flag || ''} ${country.name} ${country.code}`.trim();
}

function countryByCode(code) {
  return PHONE_COUNTRIES.find(c => c.code === code) || PHONE_COUNTRIES[0];
}

function countryByNameAndCode(name, code) {
  return PHONE_COUNTRIES.find(c => c.name === name && c.code === code) || countryByCode(code);
}

function phoneWidget(widget = 'user') {
  return document.querySelector(`[data-phone-widget="${widget}"]`);
}

function selectCountry(widget = 'user', code = '+961', name = '') {
  const root = phoneWidget(widget);
  if (!root) return;
  const country = name ? countryByNameAndCode(name, code) : countryByCode(code);
  root.dataset.code = country.code;
  root.dataset.name = country.name;
  const label = document.getElementById(`${widget}CountryLabel`);
  if (label) label.textContent = countryLabel(country);
  const search = document.querySelector(`[data-country-search="${widget}"]`);
  if (search) search.value = '';
  renderCountryOptions(widget, '');
  syncUserPhoneHidden();
}

function getCountryCode(widget = 'user') {
  return phoneWidget(widget)?.dataset.code || '+961';
}

function getCountryName(widget = 'user') {
  return phoneWidget(widget)?.dataset.name || 'Lebanon';
}

function renderCountryOptions(widget = 'user', query = '') {
  const box = document.querySelector(`[data-country-options="${widget}"]`);
  if (!box) return;
  const q = String(query || '').trim().toLowerCase();
  const selectedCode = getCountryCode(widget);
  const selectedName = getCountryName(widget);
  const rows = PHONE_COUNTRIES.filter(c => !q || `${c.name} ${c.code}`.toLowerCase().includes(q));
  box.innerHTML = rows.map(c => `
    <button class="country-option-pro ${c.code === selectedCode && c.name === selectedName ? 'is-selected' : ''}" type="button" data-country-code="${Pyrk.esc(c.code)}" data-country-name="${Pyrk.esc(c.name)}" role="option">
      <span>${Pyrk.esc(c.flag)} ${Pyrk.esc(c.name)}</span>
      <strong>${Pyrk.esc(c.code)}</strong>
    </button>`).join('') || '<p class="muted country-empty">No country found.</p>';
}

function openCountryDropdown(widget = 'user') {
  document.querySelectorAll('.country-dropdown-pro').forEach(menu => menu.hidden = true);
  document.querySelectorAll('[data-country-button]').forEach(btn => btn.setAttribute('aria-expanded', 'false'));
  const menu = document.querySelector(`[data-country-menu="${widget}"]`);
  const btn = document.querySelector(`[data-country-button="${widget}"]`);
  if (!menu) return;
  renderCountryOptions(widget, '');
  menu.hidden = false;
  if (btn) btn.setAttribute('aria-expanded', 'true');
  setTimeout(() => document.querySelector(`[data-country-search="${widget}"]`)?.focus(), 30);
}

function closeCountryDropdowns() {
  document.querySelectorAll('.country-dropdown-pro').forEach(menu => menu.hidden = true);
  document.querySelectorAll('[data-country-button]').forEach(btn => btn.setAttribute('aria-expanded', 'false'));
}

function splitPhone(value, fallbackCode = '+961') {
  const raw = String(value || '').trim();
  if (!raw) return {code: fallbackCode, name: countryByCode(fallbackCode).name, number: ''};
  const compact = raw.replace(/[^\d+]/g, '');
  const codes = [...new Set(PHONE_COUNTRIES.map(c => c.code))].sort((a, b) => b.length - a.length);
  if (compact.startsWith('+')) {
    const code = codes.find(c => compact.startsWith(c)) || fallbackCode;
    return {code, name: countryByCode(code).name, number: compact.slice(code.length).replace(/^0+/, '')};
  }
  return {code: fallbackCode, name: countryByCode(fallbackCode).name, number: compact.replace(/^0+/, '')};
}

function setPhoneInputs(fullValue) {
  const parts = splitPhone(fullValue, '+961');
  selectCountry('user', parts.code, parts.name);
  const number = document.getElementById('userMobileNumber');
  if (number) number.value = parts.number;
  syncUserPhoneHidden();
}

function syncUserPhoneHidden() {
  const code = getCountryCode('user');
  const number = String(document.getElementById('userMobileNumber')?.value || '').replace(/[^\d]/g, '').replace(/^0+/, '');
  const hidden = document.getElementById('userMobile');
  if (hidden) hidden.value = number ? `${code}${number}` : '';
}

function profileField(label, value) {
  return `<div class="profile-field-row"><span>${Pyrk.esc(label)}</span><strong>${value && String(value).trim() ? Pyrk.esc(value) : '—'}</strong></div>`;
}

function profileFieldHtml(label, html) {
  return `<div class="profile-field-row"><span>${Pyrk.esc(label)}</span><strong>${html || '—'}</strong></div>`;
}



function splitPersonName(fullName) {
  const parts = String(fullName || '').trim().replace(/\s+/g, ' ').split(' ').filter(Boolean);
  if (!parts.length) return { first_name: '', last_name: '' };
  return { first_name: parts.shift() || '', last_name: parts.join(' ') };
}

function personFirstName(person) {
  const first = String(person?.first_name || '').trim();
  if (first) return first;
  return splitPersonName(person?.full_name || '').first_name;
}

function personLastName(person) {
  const last = String(person?.last_name || '').trim();
  if (last) return last;
  return splitPersonName(person?.full_name || '').last_name;
}

function personDisplayName(person, fallback = 'User') {
  const full = `${personFirstName(person)} ${personLastName(person)}`.trim();
  return full || String(person?.display_name || person?.full_name || fallback).trim() || fallback;
}

function syncPersonNameHidden(firstId, lastId, fullId) {
  const first = document.getElementById(firstId);
  const last = document.getElementById(lastId);
  const full = document.getElementById(fullId);
  if (!first || !last || !full) return '';
  full.value = `${first.value || ''} ${last.value || ''}`.trim().replace(/\s+/g, ' ');
  return full.value;
}


function roleLabel(role) {
  return String(role || '').replace(/_/g, ' ').replace(/\b\w/g, m => m.toUpperCase());
}

function publicAsset(path) {
  if (!path) return '';
  if (/^https?:\/\//.test(path)) return path;
  return (window.PYRK_PUBLIC_BASE || '../') + String(path).replace(/^\/+/, '');
}

function initials(name) {
  return String(name || 'U').trim().split(/\s+/).slice(0,2).map(p => p[0] || '').join('').toUpperCase() || 'U';
}

function avatarHtml(person, sizeClass = '') {
  if (person.profile_photo_path) {
    return `<img class="avatar-img ${sizeClass}" src="${Pyrk.esc(publicAsset(person.profile_photo_path))}" alt="${Pyrk.esc(personDisplayName(person, 'User'))}">`;
  }
  return `<div class="avatar ${sizeClass}">${Pyrk.esc(initials(personDisplayName(person, 'User')))}</div>`;
}

function defaultPermissionsForRole(roleName) {
  if (roleName === 'super_admin') return permissionCatalog.flatMap(g => (g.items || []).map(i => i.key));
  if (roleName === 'event_manager') return [
    'routes.manage','walks.manage','attendance.manage','members.view','members.manage','groups.manage',
    'loyalty.manage','rewards.manage','badges.manage','photo_contest.manage','reports.view','branding.manage'
  ];
  if (roleName === 'walk_leader') return ['attendance.manage','members.view','reports.view','photo_contest.manage'];
  return [];
}

function roleNameFromSelectedRole() {
  const id = String(document.getElementById('userRoleSelect').value || '');
  const role = allRoles.find(r => String(r.id) === id);
  return role ? role.name : '';
}

function fillRoleSelects() {
  const roleOptions = allRoles.map(r => `<option value="${r.id}">${roleLabel(r.name)}</option>`).join('');
  const roleSelect = document.getElementById('userRoleSelect');
  const roleFilter = document.getElementById('userRoleFilter');
  if (roleSelect) roleSelect.innerHTML = roleOptions;
  if (roleFilter) roleFilter.innerHTML = '<option value="">All roles</option>' + allRoles.map(r => `<option value="${r.name}">${roleLabel(r.name)}</option>`).join('');
}

function renderPermissionsGrid(selectedKeys = []) {
  const selected = new Set((selectedKeys || []).map(String));
  const grid = document.getElementById('permissionsGrid');
  if (!grid) return;
  grid.innerHTML = permissionCatalog.map(group => {
    const items = group.items || [];
    const selectedCount = items.filter(i => selected.has(i.key)).length;
    const groupKey = Pyrk.esc(group.key || group.label || '');
    return `<section class="permission-group-card" data-permission-group="${groupKey}">
      <div class="permission-group-head">
        <div>
          <strong>${Pyrk.esc(group.label)}</strong>
          <span>${selectedCount}/${items.length}</span>
        </div>
        <div class="permission-group-actions">
          <button class="permission-mini-btn" type="button" data-permission-group-action="select">Select all</button>
          <button class="permission-mini-btn muted" type="button" data-permission-group-action="clear">Clear</button>
        </div>
      </div>
      <div class="permission-check-list">
        ${items.map(item => `
          <label class="permission-check-row ${selected.has(item.key) ? 'is-selected' : ''}">
            <input type="checkbox" name="permissions[]" value="${Pyrk.esc(item.key)}" ${selected.has(item.key) ? 'checked' : ''}>
            <span>
              <strong>${Pyrk.esc(item.label)}</strong>
              <small>${Pyrk.esc(item.key)}</small>
            </span>
          </label>`).join('')}
      </div>
    </section>`;
  }).join('');
  syncPermissionCount();
}

function selectedPermissionKeys() {
  return Array.from(document.querySelectorAll('#permissionsGrid input[type="checkbox"]:checked')).map(i => i.value);
}

function syncPermissionCount() {
  const count = selectedPermissionKeys().length;
  const countEl = document.getElementById('selectedPermissionCount');
  if (countEl) countEl.textContent = String(count);
  document.querySelectorAll('.permission-check-row').forEach(row => {
    const input = row.querySelector('input');
    row.classList.toggle('is-selected', !!input && input.checked);
  });
  document.querySelectorAll('.permission-group-card').forEach(card => {
    const checked = card.querySelectorAll('input:checked').length;
    const total = card.querySelectorAll('input').length;
    const span = card.querySelector('.permission-group-head span');
    if (span) span.textContent = `${checked}/${total}`;
  });
}

function computeUserStats() {
  document.getElementById('totalUsers').textContent = allUsers.length;
  document.getElementById('totalSuperAdmins').textContent = allUsers.filter(u => u.role_name === 'super_admin').length;
  document.getElementById('totalManagers').textContent = allUsers.filter(u => u.role_name === 'event_manager').length;
  document.getElementById('totalLeaders').textContent = allUsers.filter(u => u.role_name === 'walk_leader').length;
}

function filteredUsers() {
  const q = (document.getElementById('userSearch').value || '').toLowerCase().trim();
  const role = document.getElementById('userRoleFilter').value;
  const status = document.getElementById('userStatusFilter').value;
  return allUsers.filter(u => {
    const hay = `${personDisplayName(u, '')} ${u.first_name || ''} ${u.last_name || ''} ${u.email || ''} ${u.mobile || ''} ${u.last_login_ip || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!role || u.role_name === role) && (!status || u.status === status);
  });
}

function statusPill(status) {
  const s = String(status || 'unknown');
  const cls = s === 'active' ? 'pill-green' : (s === 'blocked' ? 'pill-red' : 'pill-muted');
  return `<span class="pill ${cls}">${Pyrk.esc(s)}</span>`;
}


function clubMetricsHtml(user) {
  const points = Number(user?.loyalty_points || 0);
  const badges = Number(user?.badges_count || 0);
  const walks = Number(user?.total_walks || 0);
  const km = Number(user?.total_kilometers || 0);
  return `
    <div class="club-metrics-cell">
      <span class="metric-pill points-pill"><strong>${points}</strong><em>pts</em></span>
      <span class="metric-pill badges-pill"><strong>${badges}</strong><em>badges</em></span>
      <small>${walks} walks · ${km.toFixed(1)} KM</small>
    </div>`;
}

function permissionPreview(u) {
  const keys = u.permissions || [];
  const first = keys.slice(0, 3).map(k => `<span class="mini-permission-pill">${Pyrk.esc(k.split('.')[0])}</span>`).join('');
  const more = keys.length > 3 ? `<span class="mini-permission-pill">+${keys.length - 3}</span>` : '';
  return `<div class="permission-preview">${first}${more}<small>${keys.length} permissions</small></div>`;
}

function loginSecurityHtml(u) {
  const failed = Number(u.failed_login_count || 0);
  const locked = u.locked_until && new Date(String(u.locked_until).replace(' ', 'T')).getTime() > Date.now();
  return `
    <div class="security-mini">
      <strong>${failed} failed</strong>
      ${locked ? `<span class="pill pill-red">Locked until ${Pyrk.esc(u.locked_until)}</span>` : '<span class="pill pill-muted">Not locked</span>'}
      ${u.last_login_ip ? `<small>IP: ${Pyrk.esc(u.last_login_ip)}</small>` : '<small>No login IP yet</small>'}
    </div>`;
}

function renderUsers() {
  const body = document.getElementById('usersTableBody');
  if (!body) return;
  try {
    const rows = filteredUsers();
    body.innerHTML = rows.map(u => `
      <tr>
        <td>
          <div class="identity-cell">
            ${avatarHtml(u)}
            <div><strong>${Pyrk.esc(personDisplayName(u, 'User'))}</strong><small>${Pyrk.esc(u.email || '')}</small></div>
          </div>
        </td>
        <td><span class="role-badge">${roleLabel(u.role_name)}</span></td>
        <td>${clubMetricsHtml(u)}</td>
        <td>${permissionPreview(u)}</td>
        <td>${statusPill(u.status)}${u.blocked_reason ? `<small>${Pyrk.esc(u.blocked_reason)}</small>` : ''}</td>
        <td>${loginSecurityHtml(u)}</td>
        <td>${Pyrk.esc(u.last_login_at || 'Never')}</td>
        <td class="table-actions">
          <button class="btn btn-light btn-small" type="button" onclick="openUserProfile(${u.id})">Profile</button>
          ${window.PYRK_CAN_EDIT_USERS ? `<button class="btn btn-light btn-small" type="button" onclick="editUser(${u.id})">Edit</button>` : ''}
          ${window.PYRK_CAN_EDIT_USERS ? (u.status === 'blocked'
            ? `<button class="btn btn-small" type="button" onclick="unblockUser(${u.id})">Unblock</button>`
            : `<button class="btn btn-danger btn-small" type="button" onclick="blockUser(${u.id})">Block</button>`) : ''}
          ${window.PYRK_CAN_EDIT_USERS && u.locked_until ? `<button class="btn btn-light btn-small" type="button" onclick="resetUserLock(${u.id})">Reset lock</button>` : ''}
          ${window.PYRK_CAN_DELETE_USERS ? `<button class="btn btn-danger btn-small" type="button" onclick="deleteUser(${u.id}, '${Pyrk.esc(personDisplayName(u, 'user')).replace(/'/g, '&#39;')}')">Delete</button>` : ''}
          <a class="btn btn-light btn-small" href="security.php?user_id=${u.id}">Logins</a>
        </td>
      </tr>`).join('') || '<tr><td colspan="8" class="muted">No system users match your filters.</td></tr>';
  } catch (err) {
    console.error('Could not render system users', err);
    body.innerHTML = `<tr><td colspan="8" class="bad">Could not display users. Please replace api/users.php and admin_users.js from the latest patch, then Ctrl + F5. ${Pyrk.esc(err.message || '')}</td></tr>`;
  }
}

function setPasswordVisible(isVisible) {
  const input = document.getElementById('userPassword');
  const btn = document.getElementById('toggleUserPassword');
  if (!input || !btn) return;
  input.type = isVisible ? 'text' : 'password';
  btn.classList.toggle('is-visible', isVisible);
  btn.setAttribute('aria-label', isVisible ? 'Hide password' : 'Show password');
  btn.title = isVisible ? 'Hide password' : 'Show password';
}

function generatePassword() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
  const symbols = '!@#$%';
  let password = '';
  for (let i = 0; i < 10; i++) password += chars[Math.floor(Math.random() * chars.length)];
  password += symbols[Math.floor(Math.random() * symbols.length)] + String(Math.floor(Math.random() * 90) + 10);
  return password.split('').sort(() => Math.random() - 0.5).join('');
}

function resetUserForm() {
  const form = document.getElementById('userForm');
  form.reset();
  syncPersonNameHidden('userFirstName', 'userLastName', 'userFullName');
  editingUserId = null;
  document.getElementById('userId').value = '';
  document.getElementById('userFormTitle').textContent = 'Create system user';
  document.getElementById('userFormSubtitle').textContent = 'Add staff information, password, role and permissions.';
  document.getElementById('userPassword').value = '';
  document.getElementById('userPassword').placeholder = 'Required for new users';
  document.getElementById('userCanEditOwnProfile').value = '1';
  setPasswordVisible(false);
  setPhoneInputs('');
  document.getElementById('userAvatarPreview').outerHTML = '<div class="avatar-preview xl" id="userAvatarPreview">U</div>';
  if (allRoles[0]) document.getElementById('userRoleSelect').value = allRoles[0].id;
  renderPermissionsGrid(defaultPermissionsForRole(roleNameFromSelectedRole()));
  Pyrk.toast('userMsg', {ok: true, message: ''});
}

function openUserModal() {
  Pyrk.openModal('userModal');
  setTimeout(() => document.getElementById('userFirstName')?.focus(), 80);
}

window.editUser = async function editUser(id) {
  const res = await Pyrk.get('users.php', {action:'detail', id});
  if (!res.ok) { alert(res.message); return; }

  const u = res.data.user || {};
  editingUserId = Number(u.id || id);
  if (res.data.permissions_catalog) permissionCatalog = res.data.permissions_catalog;

  document.getElementById('userFormTitle').textContent = 'Edit system user';
  document.getElementById('userFormSubtitle').textContent = 'Update profile, login access and permissions.';
  document.getElementById('userId').value = u.id || '';
  document.getElementById('userFirstName').value = personFirstName(u);
  document.getElementById('userLastName').value = personLastName(u);
  syncPersonNameHidden('userFirstName', 'userLastName', 'userFullName');
  document.getElementById('userEmail').value = u.email || '';
  setPhoneInputs(u.mobile || '');
  document.getElementById('userRoleSelect').value = u.role_id || '';
  document.getElementById('userStatus').value = u.status || 'active';
  document.getElementById('userCanEditOwnProfile').value = Number(u.can_edit_own_profile ?? 1) === 1 ? '1' : '0';
  document.getElementById('userPassword').value = '';
  document.getElementById('userPassword').placeholder = 'Leave empty to keep current password';
  setPasswordVisible(false);

  const preview = document.getElementById('userAvatarPreview');
  if (u.profile_photo_path) {
    preview.outerHTML = `<img class="avatar-preview xl" id="userAvatarPreview" src="${Pyrk.esc(publicAsset(u.profile_photo_path))}" alt="Preview">`;
  } else {
    preview.outerHTML = `<div class="avatar-preview xl" id="userAvatarPreview">${Pyrk.esc(initials(personDisplayName(u, 'User')))}</div>`;
  }

  renderPermissionsGrid(u.permissions || []);
  Pyrk.closeModal('userProfileModal');
  openUserModal();
};


function renderUserPermissionsProfile(keys = []) {
  if (!keys.length) return '<p class="muted">No custom permissions selected.</p>';
  return `<div class="profile-permission-grid">${keys.map(k => `<span class="mini-permission-pill">${Pyrk.esc(k)}</span>`).join('')}</div>`;
}

function renderUserLoginLogs(logs = []) {
  if (!logs.length) return '<p class="muted">No login history recorded yet.</p>';
  return `<div class="table-wrap compact-table-wrap"><table class="pro-table compact-pro-table"><thead><tr><th>Login</th><th>Status</th><th>IP</th><th>Logout</th></tr></thead><tbody>${logs.map(l => `
    <tr>
      <td><strong>${Pyrk.formatDateTime(l.login_at)}</strong><small>${Pyrk.esc((l.user_agent || '').slice(0, 80))}</small></td>
      <td>${Number(l.success || 0) === 1 ? '<span class="pill pill-green">Success</span>' : `<span class="pill pill-red">Failed</span><small>${Pyrk.esc(l.failure_reason || '')}</small>`}</td>
      <td>${Pyrk.esc(l.ip_address || '—')}</td>
      <td>${l.logout_at ? `${Pyrk.formatDateTime(l.logout_at)}<small>${Pyrk.esc(l.logout_reason || '')}</small>` : '<span class="muted">Open / unknown</span>'}</td>
    </tr>`).join('')}</tbody></table></div>`;
}

function renderUserProfile(user, loginLogs = []) {
  document.getElementById('userProfileTitle').textContent = personDisplayName(user, 'User profile');
  const locked = user.locked_until && new Date(String(user.locked_until).replace(' ', 'T')).getTime() > Date.now();
  document.getElementById('userProfileContent').innerHTML = `
    <section class="user-profile-hero-pro">
      ${avatarHtml(user, 'xl')}
      <div>
        <h3>${Pyrk.esc(personDisplayName(user, 'System user'))}</h3>
        <p class="muted">${Pyrk.esc(user.email || '')} · ${Pyrk.esc(user.mobile || 'No mobile')}</p>
        <div class="inline-controls">${statusPill(user.status)}<span class="role-badge">${roleLabel(user.role_name)}</span>${locked ? '<span class="pill pill-red">Locked</span>' : '<span class="pill pill-muted">Not locked</span>'}</div>
        ${clubMetricsHtml(user)}
      </div>
      <div class="profile-quick-actions">
        ${window.PYRK_CAN_EDIT_USERS ? `<button class="btn btn-small" type="button" onclick="editUser(${user.id})">Edit user</button>` : ''}
        <a class="btn btn-light btn-small" href="security.php?user_id=${user.id}">Security logs</a>
      </div>
    </section>

    <section class="profile-full-info-grid">
      <article class="profile-info-card-pro">
        <h4>Account</h4>
        ${profileField('User ID', `#${user.id}`)}
        ${profileField('First Name', personFirstName(user))}
        ${profileField('Last Name', personLastName(user))}
        ${profileField('Email', user.email)}
        ${profileField('Mobile', user.mobile)}
        ${profileFieldHtml('Role', `<span class="role-badge">${roleLabel(user.role_name)}</span>`)}
        ${profileFieldHtml('Status', statusPill(user.status))}
        ${profileField('Self-profile editing', Number(user.can_edit_own_profile ?? 1) === 1 ? 'Allowed on web and mobile' : 'Disabled by administrator')}
      </article>

      <article class="profile-info-card-pro">
        <h4>Security</h4>
        ${profileField('QR token', user.qr_token)}
        ${profileField('Failed attempts', user.failed_login_count || '0')}
        ${profileField('Locked until', user.locked_until ? Pyrk.formatDateTime(user.locked_until) : 'Not locked')}
        ${profileField('Last login', user.last_login_at ? Pyrk.formatDateTime(user.last_login_at) : 'Never')}
        ${profileField('Last IP', user.last_login_ip)}
        ${profileField('Blocked at', user.blocked_at ? Pyrk.formatDateTime(user.blocked_at) : '')}
        ${profileField('Blocked reason', user.blocked_reason)}
      </article>

      <article class="profile-info-card-pro">
        <h4>System dates</h4>
        ${profileField('Created', user.created_at ? Pyrk.formatDateTime(user.created_at) : '')}
        ${profileField('Updated', user.updated_at ? Pyrk.formatDateTime(user.updated_at) : '')}
      </article>

      <article class="profile-info-card-pro">
        <h4>Permissions</h4>
        ${renderUserPermissionsProfile(user.permissions || [])}
      </article>
    </section>

    <section class="profile-panel">
      <div class="section-head"><h3>Login activity</h3><a class="btn btn-small btn-light" href="security.php?user_id=${user.id}">Open security center</a></div>
      ${renderUserLoginLogs(loginLogs)}
    </section>`;
}

window.openUserProfile = async function openUserProfile(id) {
  Pyrk.openModal('userProfileModal');
  document.getElementById('userProfileTitle').textContent = 'User profile';
  document.getElementById('userProfileContent').innerHTML = '<p class="muted">Loading profile...</p>';
  const res = await Pyrk.get('users.php', {action:'detail', id});
  if (!res.ok) {
    document.getElementById('userProfileContent').innerHTML = `<div class="notice bad"><strong>Could not load profile.</strong><br>${Pyrk.esc(res.message || 'Unknown API error.')}</div>`;
    return;
  }
  renderUserProfile(res.data.user || {}, res.data.login_logs || []);
};


window.deleteUser = async function deleteUser(id, name = 'this user') {
  if (!window.PYRK_CAN_DELETE_USERS) { alert('You do not have permission to delete users.'); return; }
  const confirmed = confirm(`Delete ${name} permanently?\n\nThis action cannot be undone.`);
  if (!confirmed) return;
  const res = await Pyrk.post('users.php', {action:'delete', id});
  alert(res.message || (res.ok ? 'Deleted' : 'Error'));
  if (res.ok) await loadUsers();
};

window.blockUser = async function blockUser(id) {
  const reason = prompt('Reason for blocking this system user:', 'Blocked by admin');
  if (reason === null) return;
  const res = await Pyrk.post('users.php', {action:'block', id, reason});
  alert(res.message || (res.ok ? 'Blocked' : 'Error'));
  await loadUsers();
};

window.unblockUser = async function unblockUser(id) {
  if (!confirm('Unblock this system user and set status to active?')) return;
  const res = await Pyrk.post('users.php', {action:'unblock', id});
  alert(res.message || (res.ok ? 'Unblocked' : 'Error'));
  await loadUsers();
};

window.resetUserLock = async function resetUserLock(id) {
  if (!confirm('Reset failed attempts and temporary lock for this user?')) return;
  const res = await Pyrk.post('users.php', {action:'reset_lock', id});
  alert(res.message || (res.ok ? 'Lock reset' : 'Error'));
  await loadUsers();
};

async function loadUsers() {
  const res = await Pyrk.get('users.php', {action:'list'});
  if (!res.ok) {
    document.getElementById('usersTableBody').innerHTML = `<tr><td colspan="8" class="bad">${Pyrk.esc(res.message || 'Could not load users.')}</td></tr>`;
    return;
  }
  allUsers = res.data.users || [];
  allRoles = res.data.roles || [];
  permissionCatalog = res.data.permissions_catalog || permissionCatalog || [];
  fillRoleSelects();
  computeUserStats();
  renderUsers();
}

document.getElementById('openCreateUserBtn')?.addEventListener('click', () => {
  resetUserForm();
  openUserModal();
});

document.getElementById('userSearch').addEventListener('input', renderUsers);
document.getElementById('userRoleFilter').addEventListener('change', renderUsers);
document.getElementById('userStatusFilter').addEventListener('change', renderUsers);

document.getElementById('userRoleSelect').addEventListener('change', () => {
  if (!editingUserId) renderPermissionsGrid(defaultPermissionsForRole(roleNameFromSelectedRole()));
});

document.getElementById('permissionsGrid').addEventListener('change', e => {
  if (e.target.matches('input[type="checkbox"]')) syncPermissionCount();
});

document.getElementById('permissionsGrid').addEventListener('click', e => {
  const btn = e.target.closest('[data-permission-group-action]');
  if (!btn) return;
  e.preventDefault();
  const card = btn.closest('.permission-group-card');
  if (!card) return;
  const shouldCheck = btn.dataset.permissionGroupAction === 'select';
  card.querySelectorAll('input[type="checkbox"]').forEach(input => {
    input.checked = shouldCheck;
  });
  syncPermissionCount();
});

document.getElementById('selectRoleDefaultsBtn').addEventListener('click', () => {
  renderPermissionsGrid(defaultPermissionsForRole(roleNameFromSelectedRole()));
});

document.getElementById('selectAllPermissionsBtn').addEventListener('click', () => {
  document.querySelectorAll('#permissionsGrid input[type="checkbox"]').forEach(input => input.checked = true);
  syncPermissionCount();
});

document.getElementById('clearPermissionsBtn').addEventListener('click', () => {
  document.querySelectorAll('#permissionsGrid input[type="checkbox"]').forEach(input => input.checked = false);
  syncPermissionCount();
});

document.getElementById('toggleUserPassword').addEventListener('click', () => {
  const input = document.getElementById('userPassword');
  setPasswordVisible(input.type === 'password');
});

document.getElementById('generatePasswordBtn').addEventListener('click', () => {
  const input = document.getElementById('userPassword');
  input.value = generatePassword();
  setPasswordVisible(true);
  input.focus();
});

document.getElementById('userFirstName')?.addEventListener('input', () => syncPersonNameHidden('userFirstName', 'userLastName', 'userFullName'));
document.getElementById('userLastName')?.addEventListener('input', () => syncPersonNameHidden('userFirstName', 'userLastName', 'userFullName'));

document.getElementById('userProfilePhoto').addEventListener('change', e => {
  const file = e.target.files && e.target.files[0];
  if (!file) return;
  const url = URL.createObjectURL(file);
  document.getElementById('userAvatarPreview').outerHTML = `<img class="avatar-preview xl" id="userAvatarPreview" src="${url}" alt="Preview">`;
});

document.getElementById('userForm').addEventListener('submit', async e => {
  e.preventDefault();
  syncUserPhoneHidden();
  syncPersonNameHidden('userFirstName', 'userLastName', 'userFullName');
  const fd = new FormData(e.currentTarget);
  fd.set('action', document.getElementById('userId').value ? 'update' : 'create');
  fd.delete('permissions[]');
  selectedPermissionKeys().forEach(key => fd.append('permissions[]', key));

  const saveBtn = document.getElementById('saveUserBtn');
  saveBtn.disabled = true;
  saveBtn.textContent = 'Saving...';

  const res = await Pyrk.postForm('users.php', fd);
  Pyrk.toast('userMsg', res);

  saveBtn.disabled = false;
  saveBtn.textContent = 'Save system user';

  if (res.ok) {
    Pyrk.closeModal('userModal');
    await loadUsers();
  }
});


function initUserCountrySelector() {
  renderCountryOptions('user', '');
  const button = document.querySelector('[data-country-button="user"]');
  const search = document.querySelector('[data-country-search="user"]');
  const options = document.querySelector('[data-country-options="user"]');
  const number = document.getElementById('userMobileNumber');

  if (button) button.addEventListener('click', e => {
    e.preventDefault();
    openCountryDropdown('user');
  });
  if (search) search.addEventListener('input', () => renderCountryOptions('user', search.value));
  if (options) options.addEventListener('click', e => {
    const option = e.target.closest('[data-country-code]');
    if (!option) return;
    selectCountry('user', option.dataset.countryCode, option.dataset.countryName);
    closeCountryDropdowns();
  });
  if (number) number.addEventListener('input', syncUserPhoneHidden);

  document.addEventListener('click', e => {
    if (!e.target.closest('.country-select-pro')) closeCountryDropdowns();
  });

  setPhoneInputs('');
}

initUserCountrySelector();

loadUsers();
