<?php
/**
 * ============================================================================
 *  SETTINGS > ACCOUNT MANAGEMENT > USERS & TEAMS  (settings-users.php)
 * ----------------------------------------------------------------------------
 *  Mirrors the HubSpot "Users & Teams > Users" page.
 *  Tabs:  Users | Seats | Teams | Permission sets | Presets
 *  Seats / Teams / Permission sets / Presets: assets/js/settings-users-tabs.js
 *  Users: Active / Pending / Bounced / Deactivated views with counts,
 *         Seat / Last active / Team filters, search, Edit columns,
 *         Export view (CSV), sortable Name, row hover buttons
 *         (Edit permissions + Actions menu), bulk bar, Create user dialog.
 *  Behaviour: assets/js/settings-users.js     Styles: assets/css/settings.css
 *  DUMMY data below; replace with DB queries.
 * ============================================================================
 */
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/settings-ui.php';
require_login();

$user = current_user();

$SEATS = array('Sales Enterprise', 'Sales Professional', 'Service', 'Core', 'Developer', 'View-only');
$TEAMS = array('Enterprise Sales', 'Inside Sales', 'Marketing', 'Support', 'Account Management');
$PERMSETS = array('Super Admin', 'Sales Manager', 'Sales Rep', 'Marketer', 'Support Agent', 'Read only');
/* Presets start empty (HubSpot shows the empty state until one is created) */

/* DUMMY users
   status : accepted | pending | bounced        state : active | deactivated
   admin  : Super Admin (Access + Permission Sets show "Super Admin")
   last   : days since last active (null = never)   created : Y-m-d H:i            */
$STD = array('Service', 'Reports', 'Sales', 'Marketing', 'Contacts');
$MKT = array('Reports', 'Marketing', 'Contacts');
function u($name, $email, $seat, $admin, $access, $perm, $team, $extra, $status, $state, $last, $created)
{
  return compact('name', 'email', 'seat', 'admin', 'access', 'perm', 'team', 'extra', 'status', 'state', 'last', 'created');
}
$USERS = array(
  u($user['name'], $user['email'], 'Sales Enterprise', true, array(), '', '', array(), 'accepted', 'active', 0, '2025-04-01 10:15'),
  u('Aaron Shaw', 'aaron.shaw@company', 'Sales Enterprise', false, $STD, '', 'Enterprise Sales', array(), 'accepted', 'active', 0, '2023-11-08 17:25'),
  u('Alice Inman', 'alice.inman@company', 'Core', false, $MKT, 'Marketer', 'Marketing', array(), 'accepted', 'active', 2, '2026-08-25 08:51'),
  u('Andrew King', 'andrew.king@company', 'Sales Enterprise', false, $STD, 'Sales Manager', 'Enterprise Sales', array('Inside Sales'), 'accepted', 'active', 1, '2024-05-23 12:10'),
  u('Diana Morgan', 'diana.morgan@company', 'Sales Enterprise', true, array(), '', '', array(), 'accepted', 'active', 50, '2023-11-08 16:41'),
  u('Frank Adams', 'frank.adams@company', 'Sales Enterprise', false, $STD, '', 'Enterprise Sales', array(), 'accepted', 'active', 0, '2025-09-02 19:01'),
  u('Karen Reed', 'karen.reed@company', 'Core', true, array(), '', '', array(), 'accepted', 'active', 0, '2026-06-10 08:53'),
  u('Mary Jenkins', 'mary.jenkins@company', 'Sales Enterprise', false, array('Service', 'Sales', 'Marketing', 'Contacts', 'Account', 'Reports'), '', '', array(), 'accepted', 'active', 1, '2025-06-27 11:50'),
  u('Natalie Sharp', 'natalie.sharp@company', 'Service', false, array('Service', 'Contacts', 'Reports'), 'Support Agent', 'Support', array(), 'accepted', 'active', 9, '2026-06-30 12:09'),
  u('Penelope Davies', 'penelope.davies@company', 'Sales Enterprise', false, $STD, 'Sales Rep', 'Enterprise Sales', array(), 'accepted', 'active', 1, '2023-11-08 17:29'),
  u('Ryan Grant', 'ryan.grant@company', 'Sales Professional', false, array('Contacts', 'Sales'), 'Sales Rep', 'Inside Sales', array(), 'accepted', 'active', 0, '2026-09-29 00:35'),
  u('Samuel Parker', 'samuel.parker@company', 'Core', false, $MKT, 'Marketer', 'Marketing', array(), 'accepted', 'active', 64, '2026-06-10 09:24'),
  u('Robert Miller', 'robert.miller@company', 'Sales Professional', false, array('Contacts', 'Sales'), 'Sales Rep', 'Inside Sales', array(), 'pending', 'active', null, '2026-09-28 14:02'),
  u('Isaac Vaughn', 'isaac.vaughn@oldmail', 'Core', false, array('Contacts'), 'Read only', '', array(), 'bounced', 'active', null, '2026-09-20 11:40'),
  u('Victor Roberts', 'victor.roberts@company', 'View-only', false, array('Contacts', 'Reports'), 'Read only', '', array(), 'accepted', 'deactivated', 120, '2024-02-14 10:00'),
  u('Paula Norris', 'paula.norris@company', 'Service', false, array('Service', 'Contacts'), 'Support Agent', 'Support', array(), 'accepted', 'deactivated', 200, '2024-07-01 09:30'),
);

/** Which view a user belongs to. */
function user_view($u)
{
  if ($u['state'] === 'deactivated')
    return 'deactivated';
  if ($u['status'] === 'pending')
    return 'pending';
  if ($u['status'] === 'bounced')
    return 'bounced';
  return 'active';
}
function last_active_label($d)
{
  if ($d === null)
    return '--';
  if ($d === 0)
    return 'Today';
  if ($d === 1)
    return 'Yesterday';
  if ($d < 7)
    return $d . ' days ago';
  return date('M j', strtotime('-' . $d . ' days'));
}
function invite_label($s)
{
  return $s === 'pending' ? 'Invite pending' : ($s === 'bounced' ? 'Invite bounced' : 'Invite accepted');
}
function dash()
{
  return '<span class="crm-text-body-secondary">--</span>';
}

$COUNTS = array('active' => 0, 'pending' => 0, 'bounced' => 0, 'deactivated' => 0);
foreach ($USERS as $x) {
  $COUNTS[user_view($x)]++;
}

/* Seats tab: seat => limit (0 = unlimited). Counts are worked out in the browser from the user rows. */
$SEAT_LIMITS = array('View-only' => 0, 'Core' => 0, 'Developer' => 0, 'Sales Enterprise' => 19);
$SEAT_INFO = array(
  'View-only' => 'View-only users can see records and reports but cannot edit. Free and unlimited.',
  'Core' => 'Core seats give access to marketing, content and admin tools.',
  'Developer' => 'Developer seats give access to developer tools, APIs and sandboxes.',
  'Service' => 'Service seats unlock help desk, tickets and customer success tools.',
  'Sales Professional' => 'Sales Professional seats unlock sequences, quotes and forecasting.',
  'Sales Enterprise' => 'Sales Enterprise seats add playbooks, conversation intelligence and custom objects.',
);

$SEAT_SUMMARY_CONFIG = array(
  'View-only' => array('label' => 'VIEW-ONLY', 'limit' => 0, 'meta' => 'Unlimited seats', 'badge' => ''),
  'Core' => array('label' => 'CORE SEATS', 'limit' => 0, 'meta' => 'Unlimited seats', 'badge' => 'Trial'),
  'Developer' => array('label' => 'DEVELOPER', 'limit' => 0, 'meta' => 'Unlimited seats', 'badge' => ''),
  'Sales Enterprise' => array('label' => 'SALES ENTERPRISE SEATS', 'limit' => 19, 'meta' => '1 seat left', 'badge' => '', 'actions' => true),
);

/* Teams tab: name + parent team. Members come from each user's Default Team. */
$TEAM_LIST = array(
  array('name' => 'Enterprise Sales', 'parent' => ''),
  array('name' => 'Inside Sales', 'parent' => 'Enterprise Sales'),
  array('name' => 'Marketing', 'parent' => ''),
  array('name' => 'Support', 'parent' => ''),
  array('name' => 'Account Management', 'parent' => ''),
);

/* Permission sets tab. User counts come from the user rows. */
$PERM_LIST = array(
  array('name' => 'Super Admin', 'access' => array('Super Admin'), 'level' => 'Super Admin', 'builtin' => true),
  array('name' => 'Sales Manager', 'access' => array('Sales', 'Contacts', 'Reports'), 'level' => 'Admin'),
  array('name' => 'Sales Rep', 'access' => array('Sales', 'Contacts'), 'level' => 'Edit'),
  array('name' => 'Marketer', 'access' => array('Marketing', 'Contacts', 'Reports'), 'level' => 'Edit'),
  array('name' => 'Support Agent', 'access' => array('Service', 'Contacts'), 'level' => 'Edit'),
  array('name' => 'Read only', 'access' => array('Contacts', 'Reports'), 'level' => 'View'),
);

/* Table columns after Name (key => header) */
$COLUMNS = array(
  'email' => 'Email',
  'seat' => 'Seat',
  'access' => 'Access',
  'perm' => 'Permission Sets',
  'team' => 'Default Team',
  'extra' => 'Extra Teams',
  'invite' => 'Invite Status',
  'last' => 'Last Active (GMT+5:30)',
  'created' => 'Created date (GMT+5:30)',
);

$page_title = 'Users & Teams';
$page_css = array('dropdown', 'custom-select', 'settings', 'settings-pages', 'object-settings', 'components/quick-filter-add', 'view-settings', 'list-page', 'components/list-common', 'views/add-view-menu', 'components/pager', 'settings-users');
$page_js = array('settings', 'settings-pages', 'components/filter-kit', 'components/quick-filter-add', 'views/add-view-menu', 'components/pager', 'settings-users', 'settings-users-tabs');
$layout = 'app';
$active_nav = '';
$settings_active = 'users';
include __DIR__ . '/includes/header.php';
?>

<div class="settings">
  <?php include __DIR__ . '/includes/settings-nav.php'; ?>

  <div class="settings__main">
    <div class="ut-main-view" data-ut-main-view>
      <header class="set-head">
        <div>
          <h1 class="set-head__title">Users &amp; Teams</h1>
        </div>
        <div class="set-head__actions">
          <div class="dropdown" data-dropdown>
            <button type="button" class="btn-crm btn-crm--outline" data-dropdown-toggle aria-haspopup="menu"
              aria-expanded="false">Actions <?php echo icon('caret-down', 'iconSize-14'); ?></button>
            <div class="dropdown__menu" role="menu" data-dropdown-menu hidden>
              <button type="button" class="dropdown__item" role="menuitem" data-export="all">Export all users</button>
              <button type="button" class="dropdown__item" role="menuitem" data-dialog-open="#domains-dialog">Change
                user email domains</button>
            </div>
          </div>
          <div class="dropdown" data-dropdown>
            <button type="button" class="btn-crm btn-crm--primary" data-dropdown-toggle aria-haspopup="menu"
              aria-expanded="false">Add users <?php echo icon('caret-down', 'iconSize-14'); ?></button>
            <div class="dropdown__menu" role="menu" data-dropdown-menu hidden>
              <button type="button" class="dropdown__item" role="menuitem" data-dialog-open="#create-user">Create
                new</button>
              <button type="button" class="dropdown__item" role="menuitem"
                data-dialog-open="#import-users">Import</button>
            </div>
          </div>
        </div>
      </header>

      <!-- Navigation Tabs (reusing os-tabs with responsive More overflow matching settings-profile) -->
      <div class="os-tabbar crm-mb-4">
        <nav class="os-tabs" aria-label="Users and teams" data-os-tabs>
          <a class="os-tab is-active" data-os-tab="users" id="users-tab" href="#users" aria-current="page">Users</a>
          <a class="os-tab" data-os-tab="seats" id="seats-tab" href="#seats">Seats</a>
          <a class="os-tab" data-os-tab="teams" id="teams-tab" href="#teams">Teams</a>
          <a class="os-tab" data-os-tab="permission-sets" id="permission-sets-tab" href="#permission-sets">Permission sets</a>
          <a class="os-tab" data-os-tab="presets" id="presets-tab" href="#presets">Presets</a>
          <div class="os-dd os-tab-more" data-os-dd data-os-more hidden>
            <button type="button" class="os-tab" data-os-dd-toggle aria-haspopup="true" aria-expanded="false">More<?php echo icon('caret-down', 'iconSize-16'); ?></button>
            <div class="os-pop os-pop--menu os-pop--right" data-os-dd-menu hidden role="menu" data-os-more-menu></div>
          </div>
        </nav>
      </div>

      <!-- ============================================================== USERS -->
      <section id="users" role="tabpanel">
        <div class="ut-intro">
          <p class="ut-intro-text">Create new users, customize user permissions, and remove users from your account. <a
              class="link ut-ext" href="#" data-help="permissions-guide">Learn more about user
              permissions<?php echo icon('external', 'iconSize-14'); ?></a></p>
        </div>

        <!-- Top Usage / Upgrade Banner -->
        <div class="ut-upgrade-banner">
          <div class="ut-upgrade-banner__text">
            <?php echo icon('info', 'iconSize-18'); ?>
            <span>You've invited <strong><span
                  data-invited-count><?php echo $COUNTS['active'] + $COUNTS['pending']; ?></span> out of 2</strong>
              users.
              Invite more users with Starter Customer Platform.</span>
          </div>
          <a href="account-billing.php" class="btn-crm btn-crm--primary btn-crm--sm">Upgrade</a>
        </div>

        <div class="ut-shell" data-users>
          <!-- views bar (matching contacts.php & target-accounts.php with scroll arrows, close tabs & add-view popover) -->
          <div class="lp-views" data-users-views-strip>
            <button type="button" class="lp-views__arrow lp-views__arrow--prev" data-tabs-prev
              aria-label="Scroll views left" title="Scroll left" hidden>
              <?php echo icon('chevron-left', 'iconSize-14'); ?>
            </button>
            <div class="lp-views__tabs" data-views-tabs role="tablist">
              <?php foreach (array('active' => 'Active Users', 'pending' => 'Pending Invites', 'bounced' => 'Bounced Invites', 'deactivated' => 'Deactivated Users') as $k => $label) { ?>
                <div class="lp-tab<?php echo $k === 'active' ? ' is-active' : ''; ?>">
                  <button type="button" class="lp-tab__btn" role="tab"
                    aria-selected="<?php echo $k === 'active' ? 'true' : 'false'; ?>" data-view="<?php echo $k; ?>">
                    <svg class="lp-i" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
                      stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                      <rect width="18" height="18" x="3" y="3" rx="2" />
                      <path d="M3 9h18" />
                      <path d="M3 15h18" />
                      <path d="M9 3v18" />
                    </svg>
                    <span><?php echo e($label); ?></span>
                  </button>
                  <?php if ($k === 'active') { ?>
                    <button type="button" class="lp-tab__icon" data-action="view-menu"
                      aria-label="View options"><?php echo icon('chevron-down', 'iconSize-12'); ?></button>
                  <?php } ?>
                  <?php if ($k !== 'active') { ?>
                    <button type="button" class="lp-tab__icon lp-tab__x" data-action="close-view"
                      data-view-id="<?php echo $k; ?>" aria-label="Close view">
                      <?php echo icon('x', 'iconSize-12'); ?>
                    </button>
                  <?php } ?>
                </div>
              <?php } ?>
            </div>
            <button type="button" class="lp-views__arrow lp-views__arrow--next" data-tabs-next
              aria-label="Scroll views right" title="Scroll right" hidden>
              <?php echo icon('chevron-right', 'iconSize-14'); ?>
            </button>
            <div class="ta-addview-wrap">
              <button type="button" class="ta-add-view-btn" data-action="toggle-add-view-pop" aria-label="Add view"
                title="Add view" aria-expanded="false">
                <?php echo icon('plus', 'iconSize-14'); ?>
                <span data-add-view-label>Add view (4/5)</span>
              </button>
            </div>
            <div class="lp-spacer"></div>
            <a href="view-all.php" class="lp-link ta-allviews-link" data-action="open-all-views">All views</a>
          </div>

          <!-- quick filters row (built with standard lp-filters & lp-chip consistent with Contacts page) -->
          <div class="lp-filters ut-filters-row">
            <div class="ut-filters-left">
              <!-- Dynamic Quick Filter chips rendered by JS -->
              <div class="ut-dynamic-chips" data-dynamic-chips></div>

              <button type="button" class="lp-chip__btn lp-fbtn ut-clear" data-f-clear hidden>Clear all</button>

              <span class="lp-vsep" aria-hidden="true"></span>

              <!-- + Add quick filter trigger (uses window.CrmQuickFilterAdd.open) -->
              <button type="button" class="lp-round lp-round--xs" data-add-quick-filter-trigger aria-haspopup="dialog"
                aria-expanded="false" aria-label="Add quick filter" title="Add quick filter">
                <?php echo icon('plus', 'iconSize-14'); ?>
              </button>

              <!-- Edit quick filters pencil trigger (opens lp-modal--qf) -->
              <button type="button" class="lp-round lp-round--xs" data-dialog-open="#edit-quick-filters-modal"
                aria-label="Edit quick filters" title="Edit quick filters">
                <?php echo icon('pencil', 'iconSize-14'); ?>
              </button>

              <!-- Advanced filters trigger (opens FilterKit panel matching Contacts page) -->
              <button type="button" class="lp-chip__btn lp-fbtn" data-action="open-adv-filters" data-adv-filter-btn>
                <?php echo icon('slider-horizontal', 'iconSize-14'); ?>
                <span data-adv-btn-label>Advanced filters</span>
              </button>
            </div>

            <!-- Right side View Actions (Undo, Clone, Settings) matching reference video -->
            <div class="ut-view-actions">
              <button type="button" class="lp-round lp-round--xs" title="Reset view changes" data-view-undo>
                <?php echo icon('refresh', 'iconSize-14'); ?>
              </button>
              <button type="button" class="lp-round lp-round--xs" title="Clone view" data-view-clone>
                <?php echo icon('file', 'iconSize-14'); ?>
              </button>
              <button type="button" class="lp-round lp-round--xs" title="View settings" data-view-settings>
                <?php echo icon('settings', 'iconSize-14'); ?>
              </button>
            </div>
          </div>

          <!-- search, columns, export toolbar (matching lp-toolbar on contacts page) -->
          <div class="lp-toolbar ut-bar">
            <label class="lp-search ut-search">
              <span class="crm-visually-hidden">Search name or email address</span>
              <?php echo icon('search', 'iconSize-16 lp-i'); ?>
              <input type="search" placeholder="Search name or email address" autocomplete="off" data-users-search>
            </label>
            <div class="ut-bar__right">
              <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-dialog-open="#edit-columns-modal">
                <?php echo icon('layout', 'iconSize-14'); ?> Edit columns
              </button>
              <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-export="view">Export view</button>
            </div>
          </div>

          <!-- bulk actions (shows when rows are ticked) -->
          <div class="ut-bulk" data-bulk hidden>
            <strong data-bulk-count>0 selected</strong>
            <button type="button" class="link" data-bulk-action="seat">Change seat</button>
            <button type="button" class="link" data-bulk-action="team">Edit main team</button>
            <button type="button" class="link ut-danger" data-bulk-action="deactivate">Deactivate users</button>
            <button type="button" class="link" data-bulk-action="reactivate">Reactivate users</button>
          </div>

          <div class="lp-tablewrap" data-users-tablewrap>
            <table class="lp-table ut-table" data-users-table>
              <thead>
                <tr>
                  <th class="lp-th lp-th--check col-check"><label class="check"><input type="checkbox"
                        data-users-all><span class="check__box" aria-hidden="true"></span><span
                        class="crm-visually-hidden">Select
                        all</span></label></th>
                  <th class="lp-th lp-th--name ut-col-name"><button type="button" class="lp-th__sort ut-sort" data-sort
                      aria-label="Sort by name"><span class="lp-th__lbl">Name</span>
                      <span class="lp-th__arrow" data-sort-icon aria-hidden="true">&uarr;</span></button></th>
                  <?php foreach ($COLUMNS as $k => $label) { ?>
                    <th class="lp-th" data-col="<?php echo $k; ?>">
                      <div class="lp-th__in"><span class="lp-th__lbl"><?php echo e($label); ?></span></div>
                    </th><?php } ?>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($USERS as $i => $x) {
                  $self = ($x['email'] === $user['email']); ?>
                  <tr class="lp-tr" data-user data-uid="u<?php echo $i; ?>" data-view="<?php echo user_view($x); ?>"
                    data-status="<?php echo e($x['status']); ?>" data-name="<?php echo e($x['name']); ?>"
                    data-email="<?php echo e(strtolower($x['email'])); ?>" data-seat="<?php echo e($x['seat']); ?>"
                    data-team="<?php echo e($x['team']); ?>"
                    data-last="<?php echo $x['last'] === null ? 'never' : (int) $x['last']; ?>"
                    data-admin="<?php echo $x['admin'] ? '1' : '0'; ?>"
                    data-access="<?php echo e(implode(', ', $x['access'])); ?>" data-perm="<?php echo e($x['perm']); ?>"
                    data-extra="<?php echo e(implode(', ', $x['extra'])); ?>" <?php echo $self ? ' data-self="1"' : ''; ?>>
                    <td class="lp-td lp-td--check"><label class="check"><input type="checkbox" data-user-check><span
                          class="check__box" aria-hidden="true"></span><span class="crm-visually-hidden">Select
                          <?php echo e($x['name']); ?></span></label></td>
                    <td class="lp-td lp-td--name ut-col-name">
                      <div class="ut-name">
                        <?php echo avatar($x['name'], 'sm'); ?>
                        <a class="ut-name__link" href="#" data-user-profile><?php echo e($x['name']); ?></a>
                        <span class="ut-tag" data-admin-tag<?php echo $x['admin'] ? '' : ' hidden'; ?>>Super Admin</span>
                        <span class="ut-hover">
                          <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-edit-perms>Edit
                            permissions</button>
                          <span class="row-menu">
                            <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-row-menu
                              aria-haspopup="menu"
                              aria-expanded="false">Actions<?php echo icon('caret-down', 'iconSize-14'); ?></button>
                            <span class="row-menu__list" role="menu" hidden></span>
                          </span>
                        </span>
                      </div>
                    </td>
                    <td class="lp-td" data-col="email"><?php echo e($x['email']); ?></td>
                    <td class="lp-td" data-col="seat" data-cell="seat"><?php echo e($x['seat']); ?></td>
                    <td class="lp-td" data-col="access" data-cell="access">
                      <?php echo $x['admin'] ? 'Super Admin' : ($x['access'] ? '<span class="ut-wrap">' . e(implode(', ', $x['access'])) . '</span>' : dash()); ?>
                    </td>
                    <td class="lp-td" data-col="perm" data-cell="perm">
                      <?php echo $x['admin'] ? 'Super Admin' : ($x['perm'] !== '' ? e($x['perm']) : dash()); ?>
                    </td>
                    <td class="lp-td" data-col="team" data-cell="team">
                      <?php echo $x['team'] !== '' ? e($x['team']) : dash(); ?></td>
                    <td class="lp-td" data-col="extra" data-cell="extra">
                      <?php echo $x['extra'] ? e(implode(', ', $x['extra'])) : dash(); ?>
                    </td>
                    <td class="lp-td" data-col="invite" data-cell="invite"><span
                        class="ut-invite ut-invite--<?php echo e($x['status']); ?>"><?php echo invite_label($x['status']); ?></span>
                    </td>
                    <td class="lp-td" data-col="last"><?php echo e(last_active_label($x['last'])); ?></td>
                    <td class="lp-td" data-col="created" class="crm-text-body-secondary">
                      <?php echo e(date('F j, Y g:i A', strtotime($x['created']))); ?>
                    </td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
            <div data-users-empty hidden>
              <?php echo empty_state('users-empty', 'No users match', 'Try a different name, email or filter.', 'user', false); ?>
            </div>
          </div>
          <nav class="crm-pager" data-users-pager aria-label="Pagination"></nav>
          <footer class="vs-foot ut-vs-foot" data-users-bottom-bar>
            <span class="vs-foot__count" data-users-foot aria-live="polite">12 users</span>
            <span class="vs-spacer"></span>
            <button type="button" class="vs-round" data-action="refresh-users" aria-label="Refresh" title="Refresh">
              <?php echo icon('refresh', 'iconSize-16'); ?>
            </button>
            <button type="button" class="vs-pill" data-export="view">
              <?php echo icon('download', 'iconSize-14'); ?>Export
            </button>
            <!-- <div class="vs-split" role="group" aria-label="View changes">
            <button type="button" data-view-undo aria-label="Reset to last save" title="Reset to last save">
              <?php echo icon('undo', 'iconSize-14'); ?>
            </button>
            <button type="button" data-view-clone aria-label="Clone to new view" title="Clone to new view">
              <?php echo icon('copy', 'iconSize-14'); ?>
            </button>
          </div> -->
          </footer>
        </div>
      </section>

      <!-- ============================================================== SEATS -->
      <section id="seats" class="crm-d-none" role="tabpanel">
        <div class="ut-seats-head">
          <p class="ut-lead crm-mb-0">This is where you can manage the seats in your account.</p>
          <a class="link ut-ext" href="account-billing.php">Swap unassigned seats
            <?php echo icon('external', 'iconSize-14'); ?></a>
        </div>

        <div class="card seat-summary" data-seat-summary>
          <?php foreach ($SEAT_SUMMARY_CONFIG as $s => $cfg) { ?>
            <div class="seat-sum" data-seat-sum="<?php echo e($s); ?>" data-limit="<?php echo (int) $cfg['limit']; ?>">
              <p class="seat-sum__label"><?php echo e($cfg['label']); ?>
                <?php if (!empty($cfg['badge'])) { ?>
                  <span class="badge badge--green crm-ms-1"><?php echo e($cfg['badge']); ?></span>
                <?php } ?>
                <span class="set-info" tabindex="0" data-tip-text="<?php echo e(isset($SEAT_INFO[$s]) ? $SEAT_INFO[$s] : $cfg['label']); ?>"
                  aria-label="<?php echo e(isset($SEAT_INFO[$s]) ? $SEAT_INFO[$s] : $cfg['label']); ?>"><?php echo icon('info', 'iconSize-14'); ?></span>
              </p>
              <p class="seat-sum__value" data-seat-value>0</p>
              <p class="seat-sum__meta" data-seat-meta><?php echo e($cfg['meta']); ?></p>
              <?php if (!empty($cfg['actions'])) { ?>
                <a class="link seat-sum__link" href="account-billing.php">Add seats</a>
                <button type="button" class="link seat-sum__link" data-remove-unassigned>Remove unassigned seats <?php echo icon('external', 'iconSize-12'); ?></button>
              <?php } ?>
            </div>
          <?php } ?>
        </div>

        <div class="ut-shell" data-seats>
          <div class="lp-filters ut-filters-row">
            <div class="ut-filters-left">
              <div class="custom-select-wrapper ut-filter-pill" data-custom-select data-type="single">
                <select class="input" data-s-seat aria-label="Filter by seat" hidden>
                  <option value="">Seat</option>
                  <?php foreach ($SEATS as $s) { ?>
                    <option value="<?php echo e($s); ?>"><?php echo e($s); ?></option>
                  <?php } ?>
                </select>
              </div>
              <div class="custom-select-wrapper ut-filter-pill" data-custom-select data-type="single">
                <select class="input" data-s-perm aria-label="Filter by permission set" hidden>
                  <option value="">Permission set</option>
                  <option value="__none">No permission set</option>
                  <?php foreach ($PERMSETS as $p) { ?>
                    <option value="<?php echo e($p); ?>"><?php echo e($p); ?></option>
                  <?php } ?>
                </select>
              </div>
              <div class="custom-select-wrapper ut-filter-pill" data-custom-select data-type="single">
                <select class="input" data-s-invite aria-label="Filter by invite status" hidden>
                  <option value="">Invite Status</option>
                  <option value="accepted">Invite accepted</option>
                  <option value="pending">Invite pending</option>
                  <option value="bounced">Invite bounced</option>
                </select>
              </div>
              <button type="button" class="lp-chip__btn lp-fbtn ut-clear" data-s-clear hidden>Clear all</button>
            </div>
          </div>
          <div class="lp-toolbar ut-bar">
            <label class="lp-search ut-search">
              <span class="crm-visually-hidden">Search name or email address</span>
              <?php echo icon('search', 'iconSize-16 lp-i'); ?>
              <input type="search" placeholder="Search name or email address" autocomplete="off" data-s-search>
            </label>
            <span class="crm-text-body-secondary crm-fs-7" data-s-count><?php
  $activeCount = count(array_filter($USERS, function($u) { return $u['state'] !== 'deactivated'; }));
  echo $activeCount . ($activeCount === 1 ? ' user' : ' users');
?></span>
          </div>
          <div class="ut-bulk" data-s-bulk hidden>
            <strong data-s-bulk-count>0 selected</strong>
            <button type="button" class="link" data-s-bulk-seat>Change seat</button>
          </div>
          <div class="lp-tablewrap" data-seats-tablewrap>
            <table class="lp-table ss-table">
              <thead>
                <tr>
                  <th class="lp-th lp-th--check col-check"><label class="check"><input type="checkbox" data-s-all><span
                        class="check__box" aria-hidden="true"></span><span class="crm-visually-hidden">Select
                        all</span></label></th>
                  <th class="lp-th lp-th--name"><button type="button" class="lp-th__sort ut-sort"
                      data-s-sort="name"><span class="lp-th__lbl">Name</span> <span data-sort-icon
                        aria-hidden="true">&uarr;</span></button></th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-s-sort="seat"><span
                        class="lp-th__lbl">Seat</span> <span data-sort-icon aria-hidden="true">&#8645;</span></button>
                  </th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-s-sort="perm"><span
                        class="lp-th__lbl">Permission Set</span> <span data-sort-icon
                        aria-hidden="true">&#8645;</span></button></th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-s-sort="invite"><span
                        class="lp-th__lbl">Invite Status</span> <span data-sort-icon
                        aria-hidden="true">&#8645;</span></button></th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-s-sort="last"><span
                        class="lp-th__lbl">Last Active</span> <span data-sort-icon
                        aria-hidden="true">&#8645;</span></button></th>
                </tr>
              </thead>
              <tbody data-s-rows>
                <?php
                foreach ($USERS as $i => $x) {
                  if ($x['state'] === 'deactivated') continue;
                  $st = $x['status'];
                  $seat = $x['seat'] ?: 'Core';
                  $isTrial = ($seat === 'Core');
                  $dotClass = ($st === 'accepted' ? 'ss-dot--accepted' : ($st === 'pending' ? 'ss-dot--pending' : 'ss-dot--bounced'));
                  $statusLabel = invite_label($st);
                  $perm = $x['admin'] ? 'Super Admin' : ($x['perm'] ?: ($x['access'] ? implode(', ', $x['access']) : ''));
                ?>
                <tr class="lp-tr" data-uid="u<?php echo $i; ?>">
                  <td class="lp-td lp-td--check">
                    <label class="check"><input type="checkbox" data-s-check value="u<?php echo $i; ?>"><span class="check__box" aria-hidden="true"></span><span class="crm-visually-hidden">Select <?php echo e($x['name']); ?></span></label>
                  </td>
                  <td class="lp-td lp-td--name">
                    <div class="ut-name ss-name-cell">
                      <span class="avatar avatar--sm" aria-hidden="true"><?php echo initials($x['name']); ?></span>
                      <div class="ss-who">
                        <a class="ut-name__link" href="#" data-user-profile><?php echo e($x['name']); ?></a>
                        <span><?php echo e($x['email']); ?></span>
                      </div>
                      <button type="button" class="btn-crm btn-crm--outline btn-crm--sm ss-change-btn" data-s-change>Change seat</button>
                    </div>
                  </td>
                  <td class="lp-td">
                    <span class="ss-seat-text"><?php echo e($seat); ?> Seat</span>
                    <?php if ($isTrial) { ?><span class="badge badge--green crm-ms-1">Trial</span><?php } ?>
                  </td>
                  <td class="lp-td"><?php echo $perm ? e($perm) : dash(); ?></td>
                  <td class="lp-td">
                    <div class="ss-status-wrap">
                      <div><span class="ss-dot <?php echo $dotClass; ?>"></span><span><?php echo e($statusLabel); ?></span></div>
                      <?php if ($st === 'pending') { ?><span class="ss-status-sub crm-d-block crm-text-body-secondary crm-fs-8">Invite not accepted</span><?php } ?>
                    </div>
                  </td>
                  <td class="lp-td"><?php echo e(last_active_label($x['last'])); ?></td>
                </tr>
                <?php } ?>
              </tbody>
            </table>
            <div data-s-empty hidden>
              <?php echo empty_state('seats-empty', 'No users match', 'Try a different name, email or filter.', 'user', false); ?>
            </div>
          </div>
        </div>
      </section>

      <!-- ============================================================== TEAMS -->
      <section id="teams" class="crm-d-none" role="tabpanel">
        <p class="ut-lead">Use Teams to organize and manage users. Teams can help control access and visibility, and
          improve your reporting capabilities. <a class="link ut-ext" href="#" data-help="teams-guide">Learn more about
            teams<?php echo icon('external', 'iconSize-14'); ?></a></p>

        <div class="ut-shell" data-teams>
          <div class="lp-toolbar ut-bar">
            <label class="lp-search ut-search">
              <span class="crm-visually-hidden">Search teams</span>
              <?php echo icon('search', 'iconSize-16 lp-i'); ?>
              <input type="search" placeholder="Search" autocomplete="off" data-t-search>
            </label>
            <div class="ut-bar__right">
              <button type="button" class="btn-crm btn-crm--outline" data-dialog-open="#import-teams">Import teams</button>
              <button type="button" class="btn-crm btn-crm--primary" data-t-new>Create team</button>
            </div>
          </div>
          <div class="ut-bulk" data-t-bulk hidden>
            <strong data-t-bulk-count>0 selected</strong>
            <button type="button" class="link" data-t-bulk-move>Move</button>
            <button type="button" class="link ut-danger" data-t-delete>Delete</button>
          </div>
          <div class="lp-tablewrap" data-teams-tablewrap>
            <table class="lp-table tt-table">
              <thead>
                <tr>
                  <th class="lp-th lp-th--check col-check"><label class="check"><input type="checkbox" data-t-all><span
                        class="check__box" aria-hidden="true"></span><span class="crm-visually-hidden">Select all
                        teams</span></label></th>
                  <th class="lp-th lp-th--name"><button type="button" class="lp-th__sort ut-sort"
                      data-t-sort="name"><span class="lp-th__lbl">Name</span> <span data-sort-icon
                        aria-hidden="true">&#8645;</span></button></th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-t-sort="members"><span
                        class="lp-th__lbl">Team members</span> <span data-sort-icon
                        aria-hidden="true">&#8645;</span></button></th>
                </tr>
              </thead>
              <tbody data-t-rows>
                <?php foreach ($TEAM_LIST as $t) {
                  $members = array_filter($USERS, function($u) use ($t) {
                    return $u['state'] !== 'deactivated' && $u['team'] === $t['name'];
                  });
                ?>
                <tr class="lp-tr" data-team-name="<?php echo e($t['name']); ?>">
                  <td class="lp-td lp-td--check">
                    <label class="check"><input type="checkbox" data-t-check><span class="check__box" aria-hidden="true"></span><span class="crm-visually-hidden">Select <?php echo e($t['name']); ?></span></label>
                  </td>
                  <td class="lp-td lp-td--name">
                    <div class="tt-name-cell">
                      <div>
                        <button type="button" class="ut-name__link tt-name" data-t-edit><?php echo e($t['name']); ?></button>
                        <?php if (!empty($t['parent'])) { ?><span class="tt-parent">Child of <?php echo e($t['parent']); ?></span><?php } ?>
                      </div>
                      <div class="tt-hover-actions">
                        <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-t-edit>Edit</button>
                        <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-t-move>Move</button>
                        <button type="button" class="btn-crm btn-crm--outline btn-crm--sm" data-t-row-delete>Delete</button>
                      </div>
                    </div>
                  </td>
                  <td class="lp-td">
                    <?php if (empty($members)) { ?>
                      <span class="crm-text-body-secondary">None</span>
                    <?php } else { ?>
                      <div class="avatar-stack">
                        <?php 
                        $slice = array_slice($members, 0, 5);
                        foreach ($slice as $m) {
                          echo avatar($m['name'], 'xs');
                        }
                        if (count($members) > 5) {
                          echo '<span class="avatar avatar--xs avatar--more">+' . (count($members) - 5) . '</span>';
                        }
                        ?>
                      </div>
                    <?php } ?>
                  </td>
                </tr>
                <?php } ?>
              </tbody>
            </table>
            <div data-t-empty hidden>
              <?php echo empty_state('teams-empty', 'No teams found', 'Create a team or try a different search.', 'user', false); ?>
            </div>
          </div>
        </div>
      </section>

      <!-- ===================================================== PERMISSION SETS -->
      <section id="permission-sets" class="crm-d-none" role="tabpanel">
        <p class="ut-lead">Create sets of access for different tasks your team does. Assign one or more to users to manage permissions in bulk.</p>
        <div class="ut-shell" data-perms>
          <div class="lp-toolbar ut-bar">
            <label class="lp-search ut-search">
              <span class="crm-visually-hidden">Search permission sets</span>
              <?php echo icon('search', 'iconSize-16 lp-i'); ?>
              <input type="search" placeholder="Search" autocomplete="off" data-p-search>
            </label>
            <div class="ut-bar__right">
              <button type="button" class="btn-crm btn-crm--primary" data-p-new>Create permission set</button>
            </div>
          </div>
          <div class="lp-tablewrap" data-perms-tablewrap>
            <table class="lp-table pp-table">
              <thead>
                <tr>
                  <th class="lp-th lp-th--name"><button type="button" class="lp-th__sort ut-sort"
                      data-p-sort="name"><span class="lp-th__lbl">Name</span> <span data-sort-icon
                        aria-hidden="true">&uarr;</span></button></th>
                  <th class="lp-th"><button type="button" class="lp-th__sort ut-sort" data-p-sort="access"><span
                        class="lp-th__lbl">Access</span> <span data-sort-icon aria-hidden="true">&#8645;</span></button>
                  </th>
                  <th class="lp-th pp-users"><button type="button" class="lp-th__sort ut-sort" data-p-sort="users"><span
                        class="lp-th__lbl">Users</span> <span data-sort-icon aria-hidden="true">&#8645;</span></button>
                  </th>
                  <th class="lp-th col-actions"><span class="crm-visually-hidden">Actions</span></th>
                </tr>
              </thead>
              <tbody data-p-rows>
                <?php foreach ($PERM_LIST as $p) {
                  $cnt = 0;
                  foreach ($USERS as $u) {
                    if ($u['state'] === 'deactivated') continue;
                    if (!empty($p['builtin']) && $u['admin']) $cnt++;
                    else if ($u['perm'] === $p['name']) $cnt++;
                  }
                ?>
                <tr class="lp-tr" data-perm-name="<?php echo e($p['name']); ?>">
                  <td class="lp-td lp-td--name">
                    <span class="crm-d-inline-flex crm-align-items-center" style="gap:6px">
                      <?php if (!empty($p['builtin'])) { ?>
                        <span class="ut-name__link"><?php echo e($p['name']); ?></span>
                        <span class="set-info" tabindex="0" data-tip-text="Built-in. Super Admins can access every tool and setting." aria-label="Built-in permission set">
                          <?php echo icon('info', 'iconSize-14'); ?>
                        </span>
                      <?php } else { ?>
                        <button type="button" class="ut-name__link tt-name" data-p-edit><?php echo e($p['name']); ?></button>
                      <?php } ?>
                    </span>
                  </td>
                  <td class="lp-td">
                    <span class="pp-access"><?php echo e(implode(', ', $p['access'])); ?></span>
                    <span class="pp-level"><?php echo e($p['level']); ?></span>
                  </td>
                  <td class="lp-td pp-users"><?php echo $cnt; ?></td>
                  <td class="lp-td col-actions">
                    <?php if (empty($p['builtin'])) { ?>
                      <button type="button" class="link ut-danger" data-p-delete>Delete</button>
                    <?php } ?>
                  </td>
                </tr>
                <?php } ?>
              </tbody>
            </table>
            <div data-p-empty hidden>
              <?php echo empty_state('perms-empty', 'No permission sets found', 'Try a different search.', 'lock', false); ?>
            </div>
          </div>
        </div>
      </section>

      <!-- ============================================================ PRESETS -->
      <section id="presets" class="crm-d-none" role="tabpanel">
        <div class="preset-empty" data-r-empty>
          <div class="preset-empty__text">
            <h2 class="preset-empty__title">Set preferences for a large group of users</h2>
            <p>Presets let you manage users all in one place. Here you can preset user preferences for everyone to have
              the same access.</p>
            <a class="link ut-ext" href="#" data-help="presets-guide">Learn more about
              presets<?php echo icon('external', 'iconSize-14'); ?></a>
            <div><button type="button" class="btn-crm btn-crm--primary crm-mt-3" data-r-new>Create preset</button></div>
          </div>
          <svg class="preset-empty__art" viewBox="0 0 220 180" aria-hidden="true" focusable="false">
            <ellipse cx="110" cy="164" rx="86" ry="10" fill="var(--surface-3)" />
            <rect x="34" y="118" width="150" height="34" rx="8" fill="var(--accent)" />
            <rect x="40" y="124" width="138" height="8" rx="4" fill="var(--surface)" opacity=".85" />
            <rect x="46" y="86" width="132" height="34" rx="8" fill="var(--brand)" />
            <rect x="52" y="92" width="120" height="8" rx="4" fill="var(--surface)" opacity=".85" />
            <rect x="58" y="56" width="110" height="32" rx="8" fill="var(--teal)" />
            <rect x="64" y="62" width="98" height="8" rx="4" fill="var(--surface)" opacity=".85" />
            <circle cx="78" cy="34" r="20" fill="var(--pink-bg)" stroke="var(--pink)" stroke-width="3" />
            <circle cx="78" cy="29" r="6" fill="var(--pink)" />
            <path d="M66 46c3-7 21-7 24 0" fill="var(--pink)" />
            <circle cx="146" cy="30" r="20" fill="var(--indigo-bg)" stroke="var(--indigo)" stroke-width="3" />
            <circle cx="146" cy="25" r="6" fill="var(--indigo)" />
            <path d="M134 42c3-7 21-7 24 0" fill="var(--indigo)" />
            <circle cx="112" cy="58" r="16" fill="var(--yellow-bg)" stroke="var(--yellow)" stroke-width="3" />
            <circle cx="112" cy="54" r="5" fill="var(--yellow)" />
            <path d="M102 68c3-6 17-6 20 0" fill="var(--yellow)" />
          </svg>
        </div>

        <div data-r-list hidden>
          <p class="ut-lead">Presets let you manage users all in one place. Set seat, permissions and team once, then
            apply the preset to new users.</p>
          <div class="ut-actions-row">
            <button type="button" class="btn-crm btn-crm--primary btn-crm--sm" data-r-new>Create preset</button>
          </div>
          <div class="ut-shell">
            <div class="lp-tablewrap" data-presets-tablewrap>
              <table class="lp-table rs-table">
                <thead>
                  <tr>
                    <th class="lp-th">Preset</th>
                    <th class="lp-th">Seat</th>
                    <th class="lp-th">Permission set</th>
                    <th class="lp-th">Default team</th>
                    <th class="lp-th">Users</th>
                    <th class="lp-th col-actions"><span class="crm-visually-hidden">Actions</span></th>
                  </tr>
                </thead>
                <tbody data-r-rows></tbody>
              </table>
            </div>
          </div>
        </div>
      </section>
    </div><!-- /.ut-main-view -->

    <!-- ======================================================= REUSABLE COMPONENT: MANAGE USER ACCESS -->
    <?php include __DIR__ . '/includes/user-access-view.php'; ?>

    <!-- ================================================= SUBVIEW: PERMISSION SET -->
    <div class="ut-subview" id="permission-set-subview" hidden>
      <header class="ut-subview-head">
        <div class="ut-subview-head__left">
          <button type="button" class="ut-subview-back" data-pset-back>
            <?php echo icon('chevron-left', 'iconSize-16'); ?> Back
          </button>
        </div>
        <div class="ut-subview-head__center">
          <div class="ut-subview-title-edit">
            <span class="ut-subview-title" data-pset-name-display>Permission set name</span>
            <button type="button" class="ut-title-edit-btn" data-pset-name-edit title="Rename permission set">
              <?php echo icon('pencil', 'iconSize-14'); ?>
            </button>
            <input type="text" class="input ut-title-inline-input" data-pset-name-input value="Permission set name"
              hidden>
          </div>
        </div>
        <div class="ut-subview-head__right">
          <button type="button" class="ut-subview-save" data-pset-save>Create</button>
        </div>
      </header>

      <nav class="ut-subview-tabs" role="tablist">
        <button type="button" class="ut-subview-tab active" role="tab" aria-selected="true"
          data-pset-tab="access">Access</button>
        <button type="button" class="ut-subview-tab" role="tab" aria-selected="false"
          data-pset-tab="review">Review</button>
        <button type="button" class="ut-subview-tab" role="tab" aria-selected="false"
          data-pset-tab="users">Users</button>
      </nav>

      <div class="ut-subview-body">
        <!-- ACCESS PANE -->
        <div class="ut-subview-pane is-active" data-pset-pane="access">
          <div class="ut-pane-intro">
            <h2 class="ut-pane-title">Create permission set</h2>
            <p class="ut-pane-desc">Create a new permission set to give tool, feature, and settings access to multiple
              users at once.</p>
          </div>

          <!-- Section: Choose how to set access -->
          <div class="ut-acc is-open" data-acc="pset-mode">
            <button type="button" class="ut-acc__head" data-acc-toggle>
              <span class="ut-acc__title-wrap">
                <?php echo icon('chevron-down', 'iconSize-16 ut-acc__arrow'); ?>
                <span class="ut-acc__title">Choose how to set access</span>
              </span>
              <span class="ut-acc__badge" data-pset-mode-badge>Start from scratch</span>
            </button>
            <div class="ut-acc__body">
              <div class="ut-access-cards ut-access-cards--3">
                <label class="ut-access-card" data-pset-card="admin">
                  <input type="radio" name="pset_mode" value="admin">
                  <div class="ut-access-card__art"><?php echo icon('lock', 'iconSize-24'); ?></div>
                  <strong class="ut-access-card__head">Make Super Admin</strong>
                  <span class="ut-access-card__desc">Super Admins can manage all users, tools, and settings.</span>
                </label>

                <label class="ut-access-card" data-pset-card="template">
                  <input type="radio" name="pset_mode" value="template">
                  <div class="ut-access-card__art"><?php echo icon('file', 'iconSize-24'); ?></div>
                  <strong class="ut-access-card__head">Start with a template</strong>
                  <span class="ut-access-card__desc">Copy another user's permissions or use a suggested set of
                    permissions based on common roles.</span>
                </label>

                <label class="ut-access-card is-selected" data-pset-card="scratch">
                  <input type="radio" name="pset_mode" value="scratch" checked>
                  <div class="ut-access-card__art"><?php echo icon('pencil', 'iconSize-24'); ?></div>
                  <strong class="ut-access-card__head">Start from scratch</strong>
                  <span class="ut-access-card__desc">Create permissions specifically for this user.</span>
                </label>
              </div>
            </div>
          </div>

          <!-- Section: Choose permissions -->
          <div class="ut-acc is-open" data-acc="pset-permissions">
            <button type="button" class="ut-acc__head" data-acc-toggle>
              <span class="ut-acc__title-wrap">
                <?php echo icon('chevron-down', 'iconSize-16 ut-acc__arrow'); ?>
                <span class="ut-acc__title">Choose permissions</span>
              </span>
              <span class="ut-acc__badge">Change permissions</span>
            </button>
            <div class="ut-acc__body ut-acc__body--nopad">
              <div class="ut-perm-editor" data-perm-editor="pset">
                <div class="ut-perm-side">
                  <label class="lp-search ut-perm-search">
                    <?php echo icon('search', 'iconSize-14 lp-i'); ?>
                    <input type="search" placeholder="Search" autocomplete="off" data-pset-perm-cat-search>
                  </label>

                  <nav class="ut-perm-cats" data-pset-perm-cats>
                    <div class="ut-perm-cat-grp is-open">
                      <div class="ut-perm-cat-grp__head" data-cat-grp-toggle>
                        <span>CRM</span>
                        <?php echo icon('chevron-down', 'iconSize-12'); ?>
                      </div>
                      <div class="ut-perm-cat-grp__items">
                        <button type="button" class="ut-perm-cat is-active" data-cat="crm-objects">CRM objects</button>
                        <button type="button" class="ut-perm-cat" data-cat="crm-tools">CRM tools</button>
                        <button type="button" class="ut-perm-cat" data-cat="custom-objects">Custom objects</button>
                      </div>
                    </div>

                    <button type="button" class="ut-perm-cat" data-cat="marketing">Marketing</button>
                    <button type="button" class="ut-perm-cat" data-cat="sales">Sales</button>
                    <button type="button" class="ut-perm-cat" data-cat="revenue">Revenue</button>
                    <button type="button" class="ut-perm-cat" data-cat="service">Service</button>
                    <button type="button" class="ut-perm-cat" data-cat="data-mgmt">Data management</button>
                    <button type="button" class="ut-perm-cat" data-cat="automation">Automation</button>
                    <button type="button" class="ut-perm-cat" data-cat="reporting">Reporting</button>
                    <button type="button" class="ut-perm-cat" data-cat="ai-features">AI features</button>

                    <div class="ut-perm-cat-grp is-open">
                      <div class="ut-perm-cat-grp__head" data-cat-grp-toggle>
                        <span>Account</span>
                        <?php echo icon('chevron-down', 'iconSize-12'); ?>
                      </div>
                      <div class="ut-perm-cat-grp__items">
                        <button type="button" class="ut-perm-cat" data-cat="account-settings">Account settings</button>
                      </div>
                    </div>
                  </nav>
                </div>

                <div class="ut-perm-main">
                  <div class="ut-perm-top-bar">
                    <button type="button" class="btn-crm btn-crm--ghost btn-crm--sm" data-pset-expand-all>
                      <span class="ut-exp-icon">-</span> Expand all permissions
                    </button>
                  </div>
                  <div class="ut-perm-items-list" data-pset-perm-items-list></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- REVIEW PANE -->
        <div class="ut-subview-pane" data-pset-pane="review">
          <div class="ut-review-toolbar">
            <div class="custom-select-wrapper ut-filter-pill" data-custom-select data-type="single">
              <select class="input" id="pset-review-filter" hidden>
                <option value="">All sections</option>
                <option value="crm-objects">CRM objects</option>
                <option value="crm-tools">CRM tools</option>
                <option value="custom-objects">Custom objects</option>
                <option value="marketing">Marketing</option>
                <option value="sales">Sales</option>
                <option value="service">Service</option>
                <option value="reporting">Reporting</option>
                <option value="account-settings">Account</option>
              </select>
            </div>
            <div class="ut-review-search-wrap">
              <input type="search" class="input ut-review-search-input" placeholder="Search" autocomplete="off"
                data-pset-review-search>
              <?php echo icon('search', 'iconSize-14 ut-review-search-icon'); ?>
            </div>
          </div>
          <div class="ut-review-groups" data-pset-review-groups></div>
        </div>

        <!-- USERS PANE -->
        <div class="ut-subview-pane" data-pset-pane="users">
          <div class="ut-pane-intro">
            <h2 class="ut-pane-title">Assign users to permission set</h2>
            <p class="ut-pane-desc">Users assigned to this set will inherit all access rules configured above.</p>
          </div>
          <label class="lp-search ut-perm-search crm-mb-3">
            <?php echo icon('search', 'iconSize-14 lp-i'); ?>
            <input type="search" placeholder="Search users" autocomplete="off" data-pset-users-search>
          </label>
          <div class="ut-pset-users-list" data-pset-users-list></div>
        </div>
      </div>
    </div>

    <!-- ======================================================= SUBVIEW: PRESET -->
    <div class="ut-subview" id="preset-subview" hidden>
      <header class="ut-subview-head">
        <div class="ut-subview-head__left">
          <button type="button" class="ut-subview-back" data-preset-back>
            <?php echo icon('chevron-left', 'iconSize-16'); ?> Back
          </button>
        </div>
        <div class="ut-subview-head__center">
          <div class="ut-subview-title-edit">
            <span class="ut-subview-title" data-preset-name-display>Name your preset</span>
            <button type="button" class="ut-title-edit-btn" data-preset-name-edit title="Rename preset">
              <?php echo icon('pencil', 'iconSize-14'); ?>
            </button>
            <input type="text" class="input ut-title-inline-input" data-preset-name-input value="Name your preset"
              hidden>
          </div>
        </div>
        <div class="ut-subview-head__right">
          <button type="button" class="ut-subview-save" data-preset-save>Save preset</button>
        </div>
      </header>

      <nav class="ut-subview-tabs" role="tablist">
        <button type="button" class="ut-subview-tab active" role="tab" aria-selected="true"
          data-preset-tab="setup">Setup</button>
        <button type="button" class="ut-subview-tab" role="tab" aria-selected="false"
          data-preset-tab="users-teams">Users &amp; Teams</button>
      </nav>

      <div class="ut-subview-body">
        <!-- SETUP PANE -->
        <div class="ut-subview-pane is-active" data-preset-pane="setup">
          <div class="ut-pane-intro">
            <h2 class="ut-pane-title">Setup</h2>
            <p class="ut-pane-desc">Users can change their default preferences at any time. User changes will override
              the preset defaults.</p>
          </div>

          <nav class="set-tabs set-tabs--sm crm-mb-4" role="tablist">
            <button type="button" class="set-tab active" data-preset-subtab="general">General</button>
            <button type="button" class="set-tab" data-preset-subtab="signature">Email Signature</button>
            <button type="button" class="set-tab" data-preset-subtab="notifications">Notifications</button>
          </nav>

          <!-- Subtab General -->
          <div class="ut-preset-subpane is-active" data-preset-subpane="general">
            <div class="card crm-p-4">
              <div class="field crm-mb-3">
                <label class="field__label">Default Homepage / Dashboard</label>
                <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                  <select class="input" id="preset-homepage" hidden>
                    <option value="contacts">Contacts</option>
                    <option value="deals">Deals &amp; Pipeline</option>
                    <option value="reports">Sales Dashboard</option>
                    <option value="tasks">Tasks Overview</option>
                  </select>
                </div>
              </div>
              <div class="field">
                <label class="field__label">Language</label>
                <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                  <select class="input" id="preset-lang" hidden>
                    <option value="en">English (US)</option>
                    <option value="es">Spanish</option>
                    <option value="fr">French</option>
                    <option value="de">German</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          <!-- Subtab Email Signature (Matching Frame 27 in video!) -->
          <div class="ut-preset-subpane" data-preset-subpane="signature" hidden>
            <div class="card ut-sig-card">
              <div class="ut-sig-card__main">
                <div class="ut-sig-card__text">
                  <h3 class="ut-sig-card__title">Email Signature</h3>
                  <p class="ut-sig-card__desc">Turn on to manage email signatures for users in this preset. This preset
                    email signature will be used in one-on-one emails throughout HubSpot CRM.</p>
                </div>
                <label class="switch">
                  <input type="checkbox" data-preset-sig-toggle>
                  <span class="switch__track"></span>
                  <span class="switch__state-label" data-sig-state-label>OFF</span>
                </label>
              </div>
              <div class="ut-sig-card__editor" data-preset-sig-editor hidden>
                <textarea class="input" rows="4"
                  placeholder="Best regards,&#10;{{user.name}}&#10;{{company.name}}"></textarea>
              </div>
            </div>
          </div>

          <!-- Subtab Notifications -->
          <div class="ut-preset-subpane" data-preset-subpane="notifications" hidden>
            <div class="card crm-p-4">
              <h3 class="crm-fs-6 crm-fw-semibold crm-mb-3">Default notification channels</h3>
              <div class="field">
                <label class="check-row">
                  <span class="check"><input type="checkbox" checked><span class="check__box"></span></span>
                  <span>Send daily email digests</span>
                </label>
              </div>
              <div class="field">
                <label class="check-row">
                  <span class="check"><input type="checkbox" checked><span class="check__box"></span></span>
                  <span>Instant alerts on new leads assigned</span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- USERS & TEAMS PANE (Matching Frames 28-29 in video!) -->
        <div class="ut-subview-pane" data-preset-pane="users-teams">
          <div class="ut-pane-intro">
            <h2 class="ut-pane-title">Add users &amp; teams to preset</h2>
            <p class="ut-pane-desc">These default preferences will be applied to all users in this preset. Once you
              apply the preset, existing users will be notified about the changes you made.</p>
          </div>

          <div class="field crm-mt-4">
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="preset-users-teams-select" hidden>
                <option value="">Search users or teams</option>
                <optgroup label="Teams">
                  <?php foreach ($TEAM_LIST as $t) { ?>
                    <option value="team:<?php echo e($t['name']); ?>"><?php echo e($t['name']); ?> (Team)</option>
                  <?php } ?>
                </optgroup>
                <optgroup label="Users">
                  <?php foreach ($USERS as $u) { ?>
                    <option value="user:<?php echo e($u['name']); ?>"><?php echo e($u['name']); ?>
                      (<?php echo e($u['email']); ?>)</option>
                  <?php } ?>
                </optgroup>
              </select>
            </div>
          </div>

          <div class="crm-mt-4">
            <p class="field__label set-label">Who does this preset apply to:
              <span class="set-info" tabindex="0"
                data-tip-text="Users and teams configured will automatically receive the preset settings."
                aria-label="Preset applies to information"><?php echo icon('info', 'iconSize-14'); ?></span>
            </p>
            <div class="ut-preset-applies" data-preset-applies-list>
              <p class="crm-text-body-secondary" data-preset-no-users>No users or teams</p>
            </div>
          </div>
        </div>
      </div>
    </div>


    <!-- data for the tabs above (read by assets/js/settings-users-tabs.js) -->
    <script type="application/json" id="ut-data"><?php echo json_encode(array(
      'teams' => $TEAM_LIST,
      'perms' => $PERM_LIST,
      'presets' => array(),
      'seats' => $SEATS,
    ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?></script>

    <!-- Create / edit team (side panel) -->
    <dialog class="set-drawer" id="team-drawer" aria-labelledby="td-title">
      <form id="team-form" class="set-drawer__form" novalidate>
        <div class="set-drawer__head">
          <h2 class="set-modal__title" id="td-title">Create team</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-drawer__body">
          <div class="field">
            <label class="field__label" for="td-name">Team name *</label>
            <input class="input" id="td-name" name="name" required maxlength="80" autocomplete="off">
            <p class="field__error">Enter a team name</p>
          </div>
          <div class="field">
            <label class="field__label set-label" for="td-parent">Parent team
              <span class="set-info" tabindex="0"
                data-tip-text="Members of a parent team can see records owned by its child teams."
                aria-label="Members of a parent team can see records owned by its child teams."><?php echo icon('info', 'iconSize-14'); ?></span></label>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="td-parent" name="parent" hidden></select>
            </div>
          </div>
          <div>
            <p class="field__label">Team Members</p>
            <p class="field__help">Customize the level of access users have to this team. <a class="link" href="#"
                data-help="team-access-guide">Learn more</a></p>
            <div class="td-members">
              <label class="settings-nav__search ut-search crm-mb-0">
                <span class="crm-visually-hidden">Search for users to add or remove</span>
                <input type="search" placeholder="Search for users to add or remove" autocomplete="off" data-td-search>
                <?php echo icon('search', 'iconSize-16'); ?>
              </label>
              <p class="td-members__count" data-td-count>0 members</p>
              <ul class="td-list" data-td-list></ul>
            </div>
          </div>
        </div>
        <div class="set-drawer__foot">
          <button type="submit" class="btn-crm btn-crm--primary" data-td-save disabled>Save</button>
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
        </div>
      </form>
    </dialog>

    <!-- Move team modal (matching reference video) -->
    <dialog class="set-modal" id="move-team-dialog" aria-labelledby="mtd-title">
      <form id="move-team-form" novalidate>
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="mtd-title">Move team</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <p class="crm-text-body-secondary crm-mb-3" data-mtd-desc>Select a new parent team for this team.</p>
          <div class="field">
            <label class="field__label" for="mtd-parent">Parent team</label>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="mtd-parent" name="parent" hidden>
                <option value="">No parent team (Top level)</option>
                <?php foreach ($TEAM_LIST as $t) { ?>
                  <option value="<?php echo e($t['name']); ?>"><?php echo e($t['name']); ?></option>
                <?php } ?>
              </select>
            </div>
          </div>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="submit" class="btn-crm btn-crm--primary">Move</button>
        </div>
      </form>
    </dialog>

    <!-- Edit permissions (side panel) - assets/js/settings-users-tabs.js -->
    <dialog class="set-drawer set-modal" id="perms-drawer" aria-labelledby="ep-title">
      <form id="perms-form" class="set-drawer__form" novalidate>
        <div class="set-drawer__head">
          <div class="ep-who">
            <span class="avatar avatar--lg" aria-hidden="true" data-ep-avatar></span>
            <div>
              <h2 class="set-modal__title" id="ep-title">Edit permissions</h2>
              <p class="field__help" data-ep-sub></p>
            </div>
          </div>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>

        <div class="set-drawer__body">
          <section class="ep-section">
            <h3 class="ep-title">Seat</h3>
            <p class="field__help">Paid seats unlock advanced tools. <span data-ep-seat-left></span></p>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single" data-ep-seat-wrapper>
              <select class="input" name="seat" data-ep-seat aria-label="Seat" hidden><?php foreach ($SEATS as $s) { ?>
                  <option><?php echo e($s); ?></option><?php } ?>
              </select>
            </div>
          </section>

          <section class="ep-section">
            <div class="set-row ep-admin">
              <div>
                <p class="set-row__title">Super Admin</p>
                <p class="set-row__desc" data-ep-admin-note>Super Admins can access every tool and setting, including
                  billing and user management.</p>
              </div>
              <label class="switch"><input type="checkbox" name="admin" data-ep-admin><span
                  class="switch__track"></span><span class="crm-visually-hidden">Super Admin</span></label>
            </div>
          </section>

          <section class="ep-section" data-ep-access-wrap>
            <h3 class="ep-title">Permission set</h3>
            <p class="field__help">Apply a saved set, or choose tools below for custom access.</p>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single" data-ep-perm-wrapper>
              <select class="input" name="perm" data-ep-perm aria-label="Permission set" hidden></select>
            </div>

            <h3 class="ep-title crm-mt-3">Access</h3>
            <ul class="ep-tools">
              <?php foreach (array(
                'Contacts' => 'Contacts, companies, deals and tickets',
                'Marketing' => 'Emails, forms, ads and campaigns',
                'Sales' => 'Sequences, quotes, meetings and forecasts',
                'Service' => 'Help desk, tickets and feedback',
                'Reports' => 'Dashboards and reports',
                'Account' => 'Account settings, integrations and users'
              ) as $tool => $desc) { ?>
                <li class="ep-tool">
                  <label class="ep-tool__main">
                    <span class="check"><input type="checkbox" name="tool" value="<?php echo e($tool); ?>"
                        data-ep-tool><span class="check__box" aria-hidden="true"></span></span>
                    <span><strong><?php echo e($tool); ?></strong><span
                        class="field__help"><?php echo e($desc); ?></span></span>
                  </label>
                  <div class="custom-select-wrapper custom-select-wrapper--sm" data-custom-select data-type="single">
                    <select class="input ep-level" name="level_<?php echo e($tool); ?>"
                      data-ep-level="<?php echo e($tool); ?>" aria-label="<?php echo e($tool); ?> access level" hidden>
                      <option>View</option>
                      <option selected>Edit</option>
                    </select>
                  </div>
                </li>
              <?php } ?>
            </ul>
          </section>

          <section class="ep-section">
            <h3 class="ep-title">Teams</h3>
            <div class="field">
              <label class="field__label" for="ep-team">Default team</label>
              <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single" data-ep-team-wrapper>
                <select class="input" id="ep-team" name="team" data-ep-team hidden></select>
              </div>
            </div>
            <p class="field__label crm-mt-3">Extra teams</p>
            <div class="ep-extra" data-ep-extra></div>
          </section>
        </div>

        <div class="set-drawer__foot">
          <button type="submit" class="btn-crm btn-crm--primary">Save</button>
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
        </div>
      </form>
    </dialog>

    <!-- Create / edit permission set -->
    <dialog class="set-modal set-modal--drawer" id="perm-dialog" aria-labelledby="pd-title">
      <form id="perm-form" novalidate>
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="pd-title">Create permission set</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <div class="field">
            <label class="field__label" for="pd-name">Name *</label>
            <input class="input" id="pd-name" name="name" required maxlength="60" autocomplete="off">
            <p class="field__error">Enter a name</p>
          </div>
          <div class="field">
            <span class="field__label">Access</span>
            <div class="pd-grid">
              <?php foreach (array('Contacts', 'Marketing', 'Sales', 'Service', 'Reports', 'Account') as $a) { ?>
                <label class="check-row crm-mt-0"><span class="check"><input type="checkbox" name="access"
                      value="<?php echo e($a); ?>"><span class="check__box"
                      aria-hidden="true"></span></span><?php echo e($a); ?></label>
              <?php } ?>
            </div>
          </div>
          <div class="field">
            <label class="field__label" for="pd-level">Level</label>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="pd-level" name="level" hidden>
                <option>View</option>
                <option selected>Edit</option>
                <option>Admin</option>
              </select>
            </div>
          </div>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="submit" class="btn-crm btn-crm--primary">Save</button>
        </div>
      </form>
    </dialog>

    <!-- Create / edit preset -->
    <dialog class="set-modal set-modal--drawer" id="preset-dialog" aria-labelledby="rd-title">
      <form id="preset-form" novalidate>
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="rd-title">Create preset</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <div class="field">
            <label class="field__label" for="rd-name">Preset name *</label>
            <input class="input" id="rd-name" name="name" required maxlength="60" autocomplete="off"
              placeholder="e.g. Sales rep">
            <p class="field__error">Enter a preset name</p>
          </div>
          <div class="set-grid">
            <div class="field">
              <label class="field__label" for="rd-seat">Seat</label>
              <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                <select class="input" id="rd-seat" name="seat" hidden><?php foreach ($SEATS as $s) { ?>
                    <option><?php echo e($s); ?></option><?php } ?>
                </select>
              </div>
            </div>
            <div class="field">
              <label class="field__label" for="rd-perm">Permission set</label>
              <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                <select class="input" id="rd-perm" name="perm" data-perm-options hidden></select>
              </div>
            </div>
            <div class="field field--full">
              <label class="field__label" for="rd-team">Default team</label>
              <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                <select class="input" id="rd-team" name="team" data-team-options hidden></select>
              </div>
            </div>
          </div>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="submit" class="btn-crm btn-crm--primary">Save</button>
        </div>
      </form>
    </dialog>

    <?php
    /* Change user email domains */
    echo su_drawer(
      'domains-dialog',
      'Change user email domains',
      '<p class="field__help crm-mb-3">Moves every user with an email on the old domain to the new one, e.g. after a rebrand. Users sign in with the new address next time.</p>'
      . su_field('Current domain', '<div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single"><select class="input" id="dm-from" name="from" hidden>' . su_opts(array('yourcompany.example', 'northwind.example')) . '</select></div>', '', false, 'dm-from')
      . su_field('New domain', '<input class="input" id="dm-to" name="to" required pattern="[a-z0-9.-]+\.[a-z]{2,}" placeholder="newcompany.example">', 'Only the part after @.', false, 'dm-to')
      . su_check('dm_notify', 'Email users about the change', true),
      'Change domain',
      'Email domain change started. Users get an email when it is done.'
    );

    /* Import users / teams */
    $__import = function ($id, $title, $cols, $what) {
      return su_drawer(
        $id,
        $title,
        '<p class="field__help crm-mb-3">Upload a CSV file with these columns: <strong>' . e($cols) . '</strong>. <button type="button" class="link" data-download="' . e(strtolower(str_replace(' ', '-', $what))) . '-template.csv" data-download-text="' . e($cols) . '">Download a template</button></p>'
        . su_field('CSV file', '<input class="input" id="' . $id . '-file" name="file" type="file" accept=".csv" required>', 'Up to 500 rows.', false, $id . '-file')
        . su_check($id . '_invite', 'Send invite emails to new users', true),
        'Import',
        ucfirst($what) . ' import started. You will get an email when it is done.'
      );
    };
    echo $__import('import-users', 'Import users', 'Email,First name,Last name,Seat,Team', 'users');
    echo $__import('import-teams', 'Import teams', 'Team name,Parent team,Team members (emails)', 'teams');
    ?>

    <!-- User profile -->
    <dialog class="set-modal set-modal--drawer" id="user-profile" aria-labelledby="up-title">
      <div>
        <?php echo su_dialog_head('User profile', 'up-title'); ?>
        <div class="set-modal__body">
          <div class="up-head">
            <span class="avatar avatar--lg" data-up-initials aria-hidden="true"></span>
            <div>
              <p class="crm-fw-semibold crm-fs-5" data-up-name></p>
              <p class="field__help" data-up-email></p>
            </div>
          </div>
          <dl class="details-list crm-mt-4" data-up-list></dl>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-up-perms>Edit permissions</button>
          <button type="button" class="btn-crm btn-crm--primary" data-dialog-close>Done</button>
        </div>
      </div>
    </dialog>

    <!-- Edit Columns 2-Column Modal (matching Contacts page lp-cols2) -->
    <dialog class="set-modal lp-modal lp-modal--wide lp-modal--cols" id="edit-columns-modal" aria-labelledby="ec-title">
      <div class="lp-modal__head">
        <h2 id="ec-title">Choose which columns you see</h2>
        <button type="button" class="lp-icon-btn" data-dialog-close
          aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
      </div>
      <div class="lp-modal__body">
        <div class="lp-cols2">
          <div class="lp-cols2__left">
            <label class="lp-cols2__search">
              <input type="search" data-c="q" placeholder="Search columns..." aria-label="Search columns"
                autocomplete="off">
              <?php echo icon('search', 'iconSize-16 lp-i'); ?>
            </label>
            <div class="lp-cols2__groups" data-c="groups"></div>
            <p class="lp-cols2__note">Don't see the property you're looking for? <a class="lp-a"
                href="settings-properties.php" target="_blank" rel="noopener">Create a property
                <?php echo icon('external', 'iconSize-12 lp-i lp-i--xs'); ?></a></p>
          </div>
          <div class="lp-cols2__right">
            <div class="lp-cols2__rh">
              <span>Selected columns (<span data-c="n"></span>)</span>
              <!-- <label class="lp-cols2__frz">
            <span>Frozen columns</span>
            <div class="custom-select-wrapper lp-cols2__frz-select" data-custom-select data-type="single" data-placeholder="0">
              <select class="input" data-c="frozen" id="lpColFrz" hidden aria-label="Frozen columns"></select>
            </div>
          </label> -->
            </div>
            <ol class="lp-cols2__sel" data-c="sel"></ol>
          </div>
        </div>
      </div>
      <footer class="lp-modal__foot">
        <div class="lp-modal__left">
          <button type="button" class="btn-crm btn-crm--ghost" data-c2="all">Remove all columns</button>
        </div>
        <div class="lp-modal__acts">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="button" class="btn-crm btn-crm--primary" data-c2="apply">Apply</button>
        </div>
      </footer>
    </dialog>

    <!-- Edit Quick Filters Modal (matching Contacts page lp-modal--qf) -->
    <dialog class="set-modal lp-modal lp-modal--qf" id="edit-quick-filters-modal" aria-labelledby="eqf-title">
      <div class="lp-modal__head">
        <h2 id="eqf-title">Edit quick filters</h2>
        <button type="button" class="lp-icon-btn" data-dialog-close
          aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
      </div>
      <div class="lp-modal__body">
        <div class="lp-qf" data-qf-container></div>
      </div>
      <footer class="lp-modal__foot">
        <div class="lp-modal__acts">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="button" class="btn-crm btn-crm--primary" data-qf-done>Done</button>
        </div>
      </footer>
    </dialog>

    <!-- Create new user drawer -->
    <dialog class="set-modal set-modal--drawer" id="create-user" aria-labelledby="cu-title">
      <form id="create-user-form" novalidate>
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="cu-title">Create a new user</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <div class="ut-drawer-top-links">
            <button type="button" class="link ut-wizard-link" data-open-wizard>Use the classic user creation wizard</button>
            <div class="ut-clone-dropdown" data-clone-dropdown>
              <button type="button" class="link ut-clone-link" data-clone-toggle aria-haspopup="menu"
                aria-expanded="false">
                <span data-clone-toggle-text>Clone an existing user</span> <?php echo icon('caret-down', 'iconSize-14'); ?>
              </button>
              <div class="ut-clone-menu" data-clone-menu hidden>
                <div class="ut-clone-search-wrap">
                  <input type="search" class="ut-clone-search-input" placeholder="Search" autocomplete="off" data-clone-search>
                  <?php echo icon('search', 'iconSize-14 ut-clone-search-icon'); ?>
                </div>
                <p class="ut-clone-title">Users</p>
                <div class="ut-clone-list" data-clone-list>
                  <?php foreach ($USERS as $cl) { 
                    $parts = explode(' ', trim($cl['name']));
                    $inits = strtoupper(substr($parts[0], 0, 1) . (isset($parts[1]) ? substr($parts[1], 0, 1) : ''));
                  ?>
                    <button type="button" class="ut-clone-item"
                      data-clone-user="<?php echo e(strtolower($cl['email'])); ?>"
                      data-name="<?php echo e($cl['name']); ?>"
                      data-seat="<?php echo e($cl['seat']); ?>"
                      data-team="<?php echo e($cl['team']); ?>"
                      data-perm="<?php echo e($cl['perm']); ?>">
                      <span class="avatar avatar--xs ut-clone-avatar"><?php echo e($inits); ?></span>
                      <span class="ut-clone-name"><?php echo e($cl['name']); ?></span>
                    </button>
                  <?php } ?>
                </div>
              </div>
            </div>
          </div>

          <div class="field">
            <label class="field__label" for="cu-email">Email address *</label>
            <p class="field__help">Add an email address(es) or import a .csv file <button type="button" class="link ut-ext-btn" data-dialog-open="#import-users">here <?php echo icon('external', 'iconSize-12'); ?></button>.</p>
            <input class="input" id="cu-email" name="email" type="text" required placeholder="Add email address">
            <p class="field__error">Enter a valid email address</p>
          </div>

          <div class="field">
            <label class="field__label" for="cu-seat-btn">Seat *</label>
            <p class="field__help">Choose a seat to give access to CRM features. <a class="link ut-ext" href="account-billing.php">Learn more <?php echo icon('external', 'iconSize-12'); ?></a></p>
            <div class="ut-drawer-seat-wrap crm-w-100" data-seat-select>
              <button type="button" class="input ut-drawer-seat-trigger" data-seat-trigger aria-haspopup="listbox" aria-expanded="false" id="cu-seat-btn">
                <span data-seat-btn-label>Choose a seat</span>
                <?php echo icon('chevron-down', 'iconSize-14 ut-drawer-seat-icon'); ?>
              </button>
              <input type="hidden" name="seat" id="cu-seat" value="">
              <div class="ut-drawer-seat-menu" data-seat-menu hidden role="listbox">
                <button type="button" class="ut-drawer-seat-opt" role="option" data-seat-val="View-only" data-seat-name="View-Only Seat">
                  <span class="ut-drawer-seat-chk" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                  </span>
                  <span class="ut-drawer-seat-info">
                    <span class="ut-drawer-seat-title">View-Only Seat</span>
                    <span class="ut-drawer-seat-sub">Unlimited seats</span>
                  </span>
                </button>
                <button type="button" class="ut-drawer-seat-opt" role="option" data-seat-val="Core" data-seat-name="Core Seat">
                  <span class="ut-drawer-seat-chk" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                  </span>
                  <span class="ut-drawer-seat-info">
                    <span class="ut-drawer-seat-title">Core Seat</span>
                    <span class="ut-drawer-seat-sub">0 left</span>
                  </span>
                </button>
                <button type="button" class="ut-drawer-seat-opt" role="option" data-seat-val="Developer" data-seat-name="Developer Seat">
                  <span class="ut-drawer-seat-chk" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                  </span>
                  <span class="ut-drawer-seat-info">
                    <span class="ut-drawer-seat-title">Developer Seat</span>
                    <span class="ut-drawer-seat-sub">Unlimited seats</span>
                  </span>
                </button>
                <button type="button" class="ut-drawer-seat-opt" role="option" data-seat-val="Sales Enterprise" data-seat-name="Sales Enterprise Seat">
                  <span class="ut-drawer-seat-chk" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                  </span>
                  <span class="ut-drawer-seat-info">
                    <span class="ut-drawer-seat-title">Sales Enterprise Seat</span>
                    <span class="ut-drawer-seat-sub">1 left</span>
                  </span>
                </button>
              </div>
            </div>
          </div>

          <div class="field">
            <label class="field__label" for="cu-perm">Permissions</label>
            <p class="field__help">Default seat permissions will be applied if no selection is made.</p>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="cu-perm" name="perm" hidden>
                <option value="Default Permissions" selected>Default Permissions</option>
                <option value="Super Admin">Super Admin</option>
                <option value="Sales Manager">Sales Manager</option>
                <option value="Sales Rep">Sales Rep</option>
                <option value="Marketer">Marketer</option>
                <option value="Support Agent">Support Agent</option>
                <option value="Read only">Read only</option>
              </select>
            </div>
          </div>

          <div class="field">
            <label class="field__label" for="cu-team">Team</label>
            <p class="field__help">Add to a team to improve collaboration and reporting.</p>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single" data-search="true" data-placeholder="Choose a team">
              <select class="input" id="cu-team" name="team" hidden>
                <option value="">No team assigned</option>
                <?php foreach ($TEAMS as $t) { ?>
                  <option value="<?php echo e($t); ?>"><?php echo e($t); ?></option>
                <?php } ?>
              </select>
            </div>
          </div>

          <div class="field">
            <label class="field__label">Invite</label>
            <label class="check-row">
              <span class="check"><input type="checkbox" name="send_invite" id="cu-invite" checked><span
                  class="check__box" aria-hidden="true"></span></span>
              <span>Send an email invite to this user.</span>
              <button type="button" class="link ut-customize-invite" data-invite-customize>Customize</button>
            </label>
          </div>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="submit" class="btn-crm btn-crm--primary">Add users</button>
        </div>
      </form>
    </dialog>

    <!-- Classic User Creation Wizard (Full 3-step wizard) -->
    <dialog class="set-modal ut-wizard-modal" id="create-user-wizard" aria-labelledby="wiz-title">
      <form id="wizard-form" class="ut-wizard-form" novalidate>
        <div class="ut-wizard-head">
          <div class="ut-wizard-head__left">
            <span class="ut-wizard-head__title">Create users</span>
          </div>
          <div class="ut-wizard-stepper">
            <div class="ut-wizard-step is-active" data-wiz-step-ind="1">
              <span class="ut-wizard-step__num">1</span>
              <span class="ut-wizard-step__title">Email</span>
            </div>
            <div class="ut-wizard-step__line"></div>
            <div class="ut-wizard-step" data-wiz-step-ind="2">
              <span class="ut-wizard-step__num">2</span>
              <span class="ut-wizard-step__title">Access</span>
            </div>
            <div class="ut-wizard-step__line"></div>
            <div class="ut-wizard-step" data-wiz-step-ind="3">
              <span class="ut-wizard-step__num">3</span>
              <span class="ut-wizard-step__title">Review</span>
            </div>
          </div>
          <div class="ut-wizard-head__right">
            <span class="ut-wizard-step-count" data-wiz-step-count>Step 1 of 3</span>
            <button type="button" class="icon-btn icon-btn--ghost" data-wiz-cancel
              aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
          </div>
        </div>

        <div class="ut-wizard-body">
          <!-- Step 1: Email -->
          <div class="ut-wizard-pane is-active" data-wiz-pane="1">
            <h2 class="ut-wizard-title" id="wiz-title">Add user email addresses</h2>
            <p class="field__help">Enter the email addresses for the users you want to add.</p>

            <div class="field crm-mt-4">
              <label class="field__label" for="wiz-email">Email addresses *</label>
              <textarea class="input ut-wizard-textarea" id="wiz-email" name="wiz_emails" rows="4" required
                placeholder="Enter email addresses separated by commas or new lines (e.g. alex@company.com, sarah@company.com)"></textarea>
              <p class="field__error">Enter at least one valid email address</p>
            </div>

            <div class="ut-wizard-import-link">
              Need to add many users? <button type="button" class="link" data-dialog-open="#import-users">Import a CSV
                file
                instead</button>
            </div>
          </div>

          <!-- Step 2: Access -->
          <div class="ut-wizard-pane" data-wiz-pane="2">
            <h2 class="ut-wizard-title">Set up user access</h2>
            <p class="field__help">Choose seat and assign permissions for these users.</p>

            <!-- Accordion 1: Assign a seat -->
            <div class="ut-wizard-acc is-open">
              <button type="button" class="ut-wizard-acc__head" data-acc-toggle>
                <span><strong>Assign a seat</strong></span>
                <?php echo icon('chevron-down', 'iconSize-16'); ?>
              </button>
              <div class="ut-wizard-acc__body">
                <div class="field">
                  <label class="field__label" for="wiz-seat">Seat type</label>
                  <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                    <select class="input" id="wiz-seat" name="wiz_seat" hidden>
                      <option value="Core">Core Seat (1 left)</option>
                      <option value="Sales Enterprise">Sales Enterprise (18 left)</option>
                      <option value="Sales Professional">Sales Professional (3 left)</option>
                      <option value="Service">Service (2 left)</option>
                      <option value="View-only">View-only (Unlimited)</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            <!-- Accordion 2: Choose how to set access -->
            <div class="ut-wizard-acc is-open">
              <button type="button" class="ut-wizard-acc__head" data-acc-toggle>
                <span><strong>Choose how to set access</strong></span>
                <?php echo icon('chevron-down', 'iconSize-16'); ?>
              </button>
              <div class="ut-wizard-acc__body">
                <div class="ut-access-cards">
                  <label class="ut-access-card is-selected">
                    <input type="radio" name="wiz_access_mode" value="seat" checked>
                    <div class="ut-access-card__icon"><?php echo icon('briefcase', 'iconSize-20'); ?></div>
                    <div class="ut-access-card__content">
                      <strong>Use seat permissions</strong>
                      <span>Give standard tools and permissions tied to their assigned seat.</span>
                    </div>
                  </label>

                  <label class="ut-access-card">
                    <input type="radio" name="wiz_access_mode" value="admin">
                    <div class="ut-access-card__icon"><?php echo icon('lock', 'iconSize-20'); ?></div>
                    <div class="ut-access-card__content">
                      <strong>Make Super Admin</strong>
                      <span>Full access to all CRM objects, tools, settings, users, and billing.</span>
                    </div>
                  </label>

                  <label class="ut-access-card">
                    <input type="radio" name="wiz_access_mode" value="template">
                    <div class="ut-access-card__icon"><?php echo icon('file', 'iconSize-20'); ?></div>
                    <div class="ut-access-card__content">
                      <strong>Start with a template</strong>
                      <span>Predefined sets for sales reps, marketers, or service agents.</span>
                    </div>
                  </label>

                  <label class="ut-access-card">
                    <input type="radio" name="wiz_access_mode" value="custom">
                    <div class="ut-access-card__icon"><?php echo icon('slider-horizontal', 'iconSize-20'); ?></div>
                    <div class="ut-access-card__content">
                      <strong>Start from scratch</strong>
                      <span>Granularly configure access for each CRM object and feature.</span>
                    </div>
                  </label>
                </div>

                <!-- Template selector (visible when template is selected) -->
                <div class="field crm-mt-3" data-wiz-template-wrap hidden>
                  <label class="field__label" for="wiz-template-select">Permission Template</label>
                  <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                    <select class="input" id="wiz-template-select" name="wiz_template" hidden>
                      <?php foreach ($PERMSETS as $p) { ?>
                        <option<?php echo $p === 'Sales Rep' ? ' selected' : ''; ?>><?php echo e($p); ?></option>
                        <?php } ?>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            <!-- Accordion 3: Granular Permissions -->
            <div class="ut-wizard-acc" data-wiz-custom-acc hidden>
              <button type="button" class="ut-wizard-acc__head" data-acc-toggle>
                <span><strong>Choose permissions</strong></span>
                <?php echo icon('chevron-down', 'iconSize-16'); ?>
              </button>
              <div class="ut-wizard-acc__body">
                <ul class="ep-tools">
                  <?php foreach (array(
                    'CRM & Contacts' => 'Contacts, companies, deals and tickets',
                    'Marketing' => 'Emails, forms, ads and campaigns',
                    'Sales' => 'Sequences, quotes, meetings and forecasts',
                    'Service' => 'Help desk, tickets and feedback',
                    'Reports' => 'Dashboards and custom reports',
                    'Account' => 'Account settings, integrations and users'
                  ) as $tool => $desc) { ?>
                    <li class="ep-tool">
                      <label class="ep-tool__main">
                        <span class="check"><input type="checkbox" name="wiz_tool" value="<?php echo e($tool); ?>"
                            checked><span class="check__box" aria-hidden="true"></span></span>
                        <span><strong><?php echo e($tool); ?></strong><span
                            class="field__help"><?php echo e($desc); ?></span></span>
                      </label>
                      <div class="custom-select-wrapper custom-select-wrapper--sm" data-custom-select data-type="single">
                        <select class="input ep-level" name="wiz_level_<?php echo e($tool); ?>" hidden>
                          <option>View</option>
                          <option selected>Edit</option>
                          <option>Admin</option>
                        </select>
                      </div>
                    </li>
                  <?php } ?>
                </ul>
              </div>
            </div>
          </div>

          <!-- Step 3: Review -->
          <div class="ut-wizard-pane" data-wiz-pane="3">
            <h2 class="ut-wizard-title">Review user and access details</h2>
            <p class="field__help">Review the summary before creating the user accounts.</p>

            <div class="ut-review-card crm-mt-4">
              <div class="ut-review-item">
                <span class="ut-review-label">Users to add:</span>
                <div class="ut-review-value" data-wiz-review-emails>--</div>
              </div>
              <div class="ut-review-item">
                <span class="ut-review-label">Seat:</span>
                <div class="ut-review-value" data-wiz-review-seat>--</div>
              </div>
              <div class="ut-review-item">
                <span class="ut-review-label">Access &amp; Permissions:</span>
                <div class="ut-review-value" data-wiz-review-perms>--</div>
              </div>
              <div class="ut-review-item">
                <span class="ut-review-label">Default team:</span>
                <div class="ut-review-value">
                  <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
                    <select class="input" id="wiz-review-team" name="wiz_team" hidden>
                      <option value="">No team assigned</option>
                      <?php foreach ($TEAMS as $t) { ?>
                        <option><?php echo e($t); ?></option>
                      <?php } ?>
                    </select>
                  </div>
                </div>
              </div>
              <div class="ut-review-item">
                <span class="ut-review-label">Invite:</span>
                <div class="ut-review-value">
                  <label class="check-row">
                    <span class="check"><input type="checkbox" name="wiz_send_invite" checked><span class="check__box"
                        aria-hidden="true"></span></span>
                    <span>Send email invitations to new users immediately</span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="ut-wizard-foot">
          <button type="button" class="btn-crm btn-crm--outline" data-wiz-cancel>Cancel</button>
          <div class="ut-wizard-foot__right">
            <button type="button" class="btn-crm btn-crm--outline" data-wiz-back hidden>Back</button>
            <button type="button" class="btn-crm btn-crm--primary" data-wiz-next>Next</button>
            <button type="submit" class="btn-crm btn-crm--primary" data-wiz-submit hidden>Create user</button>
          </div>
        </div>
      </form>
    </dialog>

    <!-- Discard changes confirmation dialog (matching reference video) -->
    <dialog class="set-modal" id="discard-wizard-dialog" aria-labelledby="dwd-title">
      <div class="set-modal__content">
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="dwd-title">Discard unsaved changes?</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <p class="crm-text-body-secondary">You have made changes that haven't been saved. Are you sure you want to
            leave this page?</p>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--primary" data-confirm-discard>Discard changes</button>
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Keep editing</button>
        </div>
      </div>
    </dialog>

    <!-- Change seat / main team (one user or bulk) -->
    <dialog class="set-modal set-modal--drawer" id="assign-dialog" aria-labelledby="as-title">
      <form id="assign-form" novalidate>
        <div class="set-modal__head">
          <h2 class="set-modal__title" id="as-title">Change seat</h2>
          <button type="button" class="icon-btn icon-btn--ghost" data-dialog-close
            aria-label="Close"><?php echo icon('x', 'iconSize-20'); ?></button>
        </div>
        <div class="set-modal__body">
          <p class="crm-text-body-secondary" data-assign-who></p>
          <div class="field" data-assign-field="seat">
            <label class="field__label" for="as-seat">Seat</label>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="as-seat" name="seat" hidden><?php foreach ($SEATS as $s) { ?>
                  <option><?php echo e($s); ?></option><?php } ?>
              </select>
            </div>
          </div>
          <div class="field" data-assign-field="team">
            <label class="field__label" for="as-team">Default team</label>
            <div class="custom-select-wrapper crm-w-100" data-custom-select data-type="single">
              <select class="input" id="as-team" name="team" hidden>
                <option value="">No team</option><?php foreach ($TEAMS as $t) { ?>
                  <option><?php echo e($t); ?></option><?php } ?>
              </select>
            </div>
          </div>
        </div>
        <div class="set-modal__foot">
          <button type="button" class="btn-crm btn-crm--outline" data-dialog-close>Cancel</button>
          <button type="submit" class="btn-crm btn-crm--primary">Save</button>
        </div>
      </form>
    </dialog>

    <?php include __DIR__ . '/includes/footer.php'; ?>