<?php
$title = 'Rôles & Permissions';
$roles = $roles ?? [];
$permissionGroups = $permissionGroups ?? [];
$rolePerms = $rolePerms ?? [];
$storage = $storage ?? 'none';
$totalModules = count($permissionGroups);
$totalPermissions = 0;
$permissionLabelMap = [];

foreach ($permissionGroups as $group) {
  $totalPermissions += count($group['permissions'] ?? []);

  foreach (($group['permissions'] ?? []) as $permission) {
    $permissionKey = (string)($permission['key_name'] ?? '');
    if ($permissionKey === '') {
      continue;
    }

    $permissionLabelMap[$permissionKey] = [
      'label' => (string)($permission['label'] ?? $permissionKey),
      'module' => (string)($group['label'] ?? 'Général'),
    ];
  }
}

$storageLabel = [
  'json' => 'Stockage JSON',
  'relational' => 'Stockage relationnel',
  'none' => 'Stockage indisponible',
][$storage] ?? 'Stockage personnalisé';

$permissionScopeMeta = static function (string $permissionKey): ?array {
  if (preg_match('/_(own)$/', $permissionKey)) {
    return ['label' => 'Mes éléments', 'class' => 'roles-scope-badge roles-scope-badge--own'];
  }

  if (preg_match('/\.(list|view|edit|delete|create)$/', $permissionKey)) {
    return ['label' => 'Tous', 'class' => 'roles-scope-badge roles-scope-badge--all'];
  }

  return null;
};
?>

<style>
  :root {
    --roles-bg: linear-gradient(180deg, #f5f7fb 0%, #eef3f9 100%);
    --roles-panel: #ffffff;
    --roles-ink: #122033;
    --roles-muted: #6b7a90;
    --roles-line: #d9e2ef;
    --roles-accent: #0f5fd7;
    --roles-accent-soft: #e9f2ff;
    --roles-accent-deep: #0a2d6f;
    --roles-ok: #0f9f6e;
    --roles-shadow: 0 18px 48px rgba(16, 31, 55, 0.08);
    --roles-shadow-soft: 0 10px 28px rgba(16, 31, 55, 0.06);
    --roles-radius: 22px;
    --roles-radius-sm: 16px;
  }

  .roles-shell {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
    padding-bottom: 2rem;
  }

  .roles-hero {
    position: relative;
    overflow: hidden;
    border-radius: 28px;
    padding: 1.75rem;
    color: #fff;
    background:
      radial-gradient(circle at top right, rgba(74, 222, 128, 0.18), transparent 22%),
      radial-gradient(circle at left center, rgba(125, 211, 252, 0.16), transparent 26%),
      linear-gradient(135deg, #0b1730 0%, #0f2b59 48%, #0f5fd7 100%);
    box-shadow: 0 24px 52px rgba(9, 30, 66, 0.22);
  }

  .roles-hero__grid {
    position: relative;
    z-index: 1;
    display: grid;
    grid-template-columns: minmax(0, 1.4fr) minmax(280px, 0.8fr);
    gap: 1.25rem;
    align-items: stretch;
  }

  .roles-hero__eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.4rem 0.75rem;
    border-radius: 999px;
    font-size: 0.78rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.14);
    color: rgba(255, 255, 255, 0.84);
  }

  .roles-hero h1 {
    margin: 0.9rem 0 0.55rem;
    font-size: clamp(1.85rem, 2vw, 2.4rem);
    font-weight: 800;
    letter-spacing: -0.04em;
  }

  .roles-hero p {
    max-width: 720px;
    margin: 0;
    color: rgba(232, 240, 255, 0.82);
    font-size: 0.98rem;
  }

  .roles-hero__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.7rem;
    margin-top: 1.15rem;
  }

  .roles-chip {
    display: inline-flex;
    align-items: center;
    gap: 0.45rem;
    padding: 0.45rem 0.75rem;
    border-radius: 999px;
    font-size: 0.78rem;
    font-weight: 600;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.12);
    color: #eef5ff;
  }

  .roles-stats {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.85rem;
    align-content: start;
  }

  .roles-stat {
    border-radius: 18px;
    padding: 1rem;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.14);
    backdrop-filter: blur(10px);
  }

  .roles-stat__value {
    font-size: 1.8rem;
    line-height: 1;
    font-weight: 800;
    letter-spacing: -0.04em;
  }

  .roles-stat__label {
    margin-top: 0.35rem;
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: rgba(233, 242, 255, 0.72);
  }

  .roles-grid {
    display: grid;
    grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
    gap: 1.5rem;
    align-items: start;
  }

  .roles-panel {
    border-radius: var(--roles-radius);
    background: var(--roles-panel);
    box-shadow: var(--roles-shadow);
    border: 1px solid rgba(217, 226, 239, 0.8);
    overflow: hidden;
  }

  .roles-panel__head {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    align-items: flex-start;
    padding: 1.35rem 1.35rem 1rem;
    border-bottom: 1px solid var(--roles-line);
    background: var(--roles-bg);
  }

  .roles-panel__eyebrow {
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    font-weight: 700;
    color: var(--roles-accent);
    margin-bottom: 0.25rem;
  }

  .roles-panel__title {
    margin: 0;
    font-size: 1.1rem;
    font-weight: 800;
    color: var(--roles-ink);
    letter-spacing: -0.03em;
  }

  .roles-panel__subtitle {
    margin: 0.35rem 0 0;
    color: var(--roles-muted);
    font-size: 0.9rem;
  }

  .roles-panel__body {
    padding: 1.35rem;
  }

  .roles-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.45rem;
    padding: 0.45rem 0.75rem;
    border-radius: 999px;
    background: #fff;
    color: var(--roles-accent-deep);
    border: 1px solid rgba(15, 95, 215, 0.16);
    font-size: 0.76rem;
    font-weight: 700;
    white-space: nowrap;
  }

  .roles-field {
    margin-bottom: 1rem;
  }

  .roles-field label {
    display: block;
    margin-bottom: 0.4rem;
    font-size: 0.8rem;
    font-weight: 700;
    color: var(--roles-ink);
  }

  .roles-input {
    width: 100%;
    border: 1px solid var(--roles-line);
    border-radius: 14px;
    padding: 0.9rem 1rem;
    background: #fff;
    color: var(--roles-ink);
    font-size: 0.95rem;
    transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease;
  }

  .roles-input:focus {
    outline: none;
    border-color: rgba(15, 95, 215, 0.44);
    box-shadow: 0 0 0 4px rgba(15, 95, 215, 0.12);
    transform: translateY(-1px);
  }

  .roles-helper {
    margin-top: 0.35rem;
    font-size: 0.78rem;
    color: var(--roles-muted);
  }

  .roles-form-tools {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
  }

  .roles-search {
    position: relative;
    flex: 1 1 220px;
  }

  .roles-search i {
    position: absolute;
    top: 50%;
    left: 1rem;
    transform: translateY(-50%);
    color: #7f90a6;
  }

  .roles-search .roles-input {
    padding-left: 2.8rem;
    background: #f9fbff;
  }

  .roles-caption {
    font-size: 0.8rem;
    color: var(--roles-muted);
  }

  .roles-groups {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    max-height: 72vh;
    overflow: auto;
    padding-right: 0.25rem;
  }

  .roles-group {
    border: 1px solid var(--roles-line);
    border-radius: var(--roles-radius-sm);
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
    box-shadow: var(--roles-shadow-soft);
  }

  .roles-group[data-hidden="true"] {
    display: none;
  }

  .roles-group__head {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 0.9rem;
    padding: 1rem 1rem 0.8rem;
    border-bottom: 1px solid rgba(217, 226, 239, 0.84);
  }

  .roles-group__title {
    margin: 0;
    font-size: 0.94rem;
    font-weight: 800;
    color: var(--roles-ink);
  }

  .roles-group__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.55rem;
    margin-top: 0.35rem;
  }

  .roles-mini-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.28rem 0.55rem;
    border-radius: 999px;
    background: var(--roles-accent-soft);
    color: var(--roles-accent-deep);
    font-size: 0.72rem;
    font-weight: 700;
  }

  .roles-group__actions {
    display: flex;
    gap: 0.55rem;
    align-items: center;
  }

  .roles-btn-inline {
    border: 0;
    background: transparent;
    color: var(--roles-accent);
    font-size: 0.78rem;
    font-weight: 700;
    padding: 0.35rem 0.45rem;
    border-radius: 10px;
    transition: background 0.18s ease, color 0.18s ease;
  }

  .roles-btn-inline:hover {
    background: var(--roles-accent-soft);
    color: var(--roles-accent-deep);
  }

  .roles-group__body {
    padding: 1rem;
  }

  .roles-permission-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 0.7rem;
  }

  .roles-permission {
    position: relative;
  }

  .roles-permission[data-hidden="true"] {
    display: none;
  }

  .roles-permission input {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
  }

  .roles-permission__card {
    display: flex;
    gap: 0.85rem;
    align-items: flex-start;
    padding: 0.9rem 0.95rem;
    border-radius: 16px;
    border: 1px solid rgba(217, 226, 239, 0.92);
    background: #fff;
    min-height: 100%;
    transition: transform 0.16s ease, box-shadow 0.16s ease, border-color 0.16s ease, background 0.16s ease;
  }

  .roles-permission__check {
    width: 20px;
    height: 20px;
    border-radius: 7px;
    border: 1.5px solid #b7c5d8;
    background: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: transparent;
    flex-shrink: 0;
    margin-top: 0.1rem;
    transition: all 0.18s ease;
  }

  .roles-permission__title {
    font-size: 0.9rem;
    font-weight: 700;
    color: var(--roles-ink);
    line-height: 1.35;
  }

  .roles-permission__topline {
    display: flex;
    flex-wrap: wrap;
    gap: 0.45rem;
    align-items: center;
  }

  .roles-scope-badge {
    display: inline-flex;
    align-items: center;
    padding: 0.18rem 0.5rem;
    border-radius: 999px;
    font-size: 0.68rem;
    font-weight: 800;
    letter-spacing: 0.04em;
    text-transform: uppercase;
  }

  .roles-scope-badge--all {
    background: #edf3ff;
    color: #1b4db3;
  }

  .roles-scope-badge--own {
    background: #e8fbf2;
    color: #0e8a5d;
  }

  .roles-permission__key {
    margin-top: 0.3rem;
    font-size: 0.74rem;
    color: var(--roles-muted);
    word-break: break-word;
  }

  .roles-permission input:checked + .roles-permission__card {
    border-color: rgba(15, 95, 215, 0.34);
    background: linear-gradient(180deg, #f7fbff 0%, #eef6ff 100%);
    box-shadow: 0 16px 28px rgba(15, 95, 215, 0.12);
    transform: translateY(-1px);
  }

  .roles-permission input:checked + .roles-permission__card .roles-permission__check {
    background: var(--roles-accent);
    border-color: var(--roles-accent);
    color: #fff;
  }

  .roles-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    margin-top: 1.1rem;
  }

  .roles-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.55rem;
    border: 0;
    border-radius: 14px;
    padding: 0.82rem 1.05rem;
    font-size: 0.88rem;
    font-weight: 700;
    text-decoration: none;
    transition: transform 0.16s ease, box-shadow 0.16s ease, opacity 0.16s ease;
  }

  .roles-btn:hover {
    transform: translateY(-1px);
    opacity: 0.96;
  }

  .roles-btn--primary {
    color: #fff;
    background: linear-gradient(135deg, var(--roles-accent), #3689ff);
    box-shadow: 0 16px 28px rgba(15, 95, 215, 0.2);
  }

  .roles-btn--secondary {
    color: var(--roles-accent-deep);
    background: #eef5ff;
  }

  .roles-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .roles-role-card {
    border: 1px solid rgba(217, 226, 239, 0.9);
    border-radius: var(--roles-radius);
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
    box-shadow: var(--roles-shadow-soft);
    overflow: hidden;
  }

  .roles-role-card__head {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    align-items: center;
    padding: 1rem 1.1rem;
    border-bottom: 1px solid rgba(217, 226, 239, 0.84);
    background: #fff;
  }

  .roles-role-card__title {
    margin: 0;
    font-size: 1rem;
    font-weight: 800;
    color: var(--roles-ink);
    letter-spacing: -0.03em;
  }

  .roles-role-card__key {
    margin-top: 0.25rem;
    font-size: 0.76rem;
    color: var(--roles-muted);
  }

  .roles-role-card__body {
    padding: 1.1rem;
  }

  .roles-role-card__summary {
    display: flex;
    flex-direction: column;
    gap: 0.85rem;
  }

  .roles-role-card__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.6rem;
  }

  .roles-role-card__preview {
    display: flex;
    flex-wrap: wrap;
    gap: 0.55rem;
  }

  .roles-preview-chip {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.45rem 0.65rem;
    border-radius: 999px;
    background: #f4f8ff;
    border: 1px solid rgba(15, 95, 215, 0.14);
    color: var(--roles-accent-deep);
    font-size: 0.74rem;
    font-weight: 700;
  }

  .roles-role-card__hint {
    margin: 0;
    color: var(--roles-muted);
    font-size: 0.84rem;
    line-height: 1.55;
  }

  .roles-role-card__actions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.65rem;
    justify-content: flex-end;
  }

  .roles-btn--ghost {
    color: var(--roles-accent-deep);
    background: #fff;
    border: 1px solid rgba(15, 95, 215, 0.16);
  }

  .roles-modal {
    position: fixed;
    inset: 0;
    z-index: 1080;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 1rem;
    background: rgba(7, 17, 34, 0.56);
    backdrop-filter: blur(8px);
  }

  .roles-modal.is-open {
    display: flex;
  }

  .roles-modal__dialog {
    width: min(820px, calc(100vw - 2rem));
    max-height: calc(100vh - 2rem);
    overflow: auto;
    border-radius: 28px;
    background: #f8fbff;
    box-shadow: 0 28px 64px rgba(5, 23, 52, 0.28);
    border: 1px solid rgba(217, 226, 239, 0.9);
  }

  .roles-modal__dialog--wide {
    width: min(1180px, calc(100vw - 2rem));
  }

  .roles-modal__header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
    padding: 1.35rem 1.4rem 1rem;
    border-bottom: 1px solid rgba(217, 226, 239, 0.88);
    background: linear-gradient(180deg, #ffffff 0%, #f4f8ff 100%);
    position: sticky;
    top: 0;
    z-index: 2;
  }

  .roles-modal__eyebrow {
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    font-weight: 700;
    color: var(--roles-accent);
    margin-bottom: 0.3rem;
  }

  .roles-modal__title {
    margin: 0;
    font-size: 1.15rem;
    font-weight: 800;
    color: var(--roles-ink);
    letter-spacing: -0.03em;
  }

  .roles-modal__subtitle {
    margin: 0.35rem 0 0;
    font-size: 0.88rem;
    color: var(--roles-muted);
  }

  .roles-modal__close {
    width: 42px;
    height: 42px;
    border-radius: 14px;
    border: 1px solid rgba(15, 95, 215, 0.16);
    background: #fff;
    color: var(--roles-accent-deep);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
  }

  .roles-modal__body {
    padding: 1.35rem 1.4rem 1.4rem;
  }

  .roles-read-layout {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .roles-read-summary {
    display: flex;
    flex-wrap: wrap;
    gap: 0.65rem;
  }

  .roles-read-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 1rem;
  }

  .roles-read-group {
    border: 1px solid rgba(217, 226, 239, 0.9);
    border-radius: 20px;
    background: #fff;
    box-shadow: var(--roles-shadow-soft);
    overflow: hidden;
  }

  .roles-read-group__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    padding: 0.95rem 1rem 0.85rem;
    border-bottom: 1px solid rgba(217, 226, 239, 0.84);
    background: linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
  }

  .roles-read-group__title {
    margin: 0;
    font-size: 0.92rem;
    font-weight: 800;
    color: var(--roles-ink);
  }

  .roles-read-list {
    padding: 0.95rem 1rem 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.65rem;
  }

  .roles-read-item {
    display: flex;
    gap: 0.75rem;
    align-items: flex-start;
    padding: 0.75rem 0.8rem;
    border-radius: 16px;
    background: #f8fbff;
    border: 1px solid rgba(217, 226, 239, 0.72);
  }

  .roles-read-item__icon {
    width: 30px;
    height: 30px;
    border-radius: 10px;
    background: var(--roles-accent-soft);
    color: var(--roles-accent);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .roles-read-item__title {
    font-size: 0.86rem;
    font-weight: 700;
    color: var(--roles-ink);
  }

  .roles-read-item__topline {
    display: flex;
    flex-wrap: wrap;
    gap: 0.45rem;
    align-items: center;
  }

  .roles-read-item__key {
    margin-top: 0.25rem;
    font-size: 0.73rem;
    color: var(--roles-muted);
    word-break: break-word;
  }

  .roles-read-empty {
    padding: 2rem 1rem;
    text-align: center;
    color: var(--roles-muted);
  }

  .roles-read-empty i {
    font-size: 1.8rem;
    color: #9db0c8;
    margin-bottom: 0.7rem;
  }

  .roles-modal .roles-panel,
  .roles-modal .roles-role-card {
    box-shadow: none;
    border-radius: 0;
    border: 0;
    background: transparent;
  }

  .roles-modal .roles-panel__head,
  .roles-modal .roles-role-card__head {
    display: none;
  }

  .roles-modal .roles-panel__body,
  .roles-modal .roles-role-card__body {
    padding: 0;
  }

  .roles-modal .roles-groups {
    max-height: none;
  }

  body.roles-modal-open {
    overflow: hidden;
  }

  .roles-empty {
    padding: 2.5rem 1.25rem;
    text-align: center;
    color: var(--roles-muted);
  }

  .roles-empty i {
    font-size: 2rem;
    margin-bottom: 0.75rem;
    color: #9db0c8;
  }

  @media (max-width: 1199.98px) {
    .roles-grid {
      grid-template-columns: 1fr;
    }

    .roles-groups {
      max-height: none;
    }
  }

  @media (max-width: 991.98px) {
    .roles-hero__grid {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 767.98px) {
    .roles-hero,
    .roles-panel__head,
    .roles-panel__body,
    .roles-role-card__head,
    .roles-role-card__body {
      padding-left: 1rem;
      padding-right: 1rem;
    }

    .roles-stats {
      grid-template-columns: 1fr;
    }

    .roles-group__head,
    .roles-form-tools {
      flex-direction: column;
      align-items: stretch;
    }

    .roles-group__actions,
    .roles-actions {
      width: 100%;
      justify-content: space-between;
    }

    .roles-role-card__head,
    .roles-modal__header {
      flex-direction: column;
      align-items: stretch;
    }

    .roles-role-card__actions {
      justify-content: stretch;
    }

    .roles-role-card__actions .roles-btn {
      flex: 1 1 auto;
      justify-content: center;
    }

    .roles-modal__body {
      padding-left: 1rem;
      padding-right: 1rem;
    }
  }
</style>

<div class="roles-shell">
  <section class="roles-hero">
    <div class="roles-hero__grid">
      <div>
        <span class="roles-hero__eyebrow"><i class="fas fa-shield-halved"></i> Gouvernance des accès</span>
        <h1>Centralisez les rôles et les permissions</h1>
        <p>La page rôles permet maintenant de parcourir les permissions par module, de filtrer rapidement les droits disponibles et de maintenir les profils d’accès dans une interface plus lisible.</p>
        <div class="roles-hero__meta">
          <span class="roles-chip"><i class="fas fa-database"></i> <?= htmlspecialchars($storageLabel) ?></span>
          <span class="roles-chip"><i class="fas fa-layer-group"></i> <?= (int)$totalModules ?> modules</span>
          <span class="roles-chip"><i class="fas fa-key"></i> <?= (int)$totalPermissions ?> permissions</span>
        </div>
      </div>

      <div class="roles-stats">
        <div class="roles-stat">
          <div class="roles-stat__value"><?= count($roles) ?></div>
          <div class="roles-stat__label">Rôles configurés</div>
        </div>
        <div class="roles-stat">
          <div class="roles-stat__value"><?= (int)$totalModules ?></div>
          <div class="roles-stat__label">Modules couverts</div>
        </div>
        <div class="roles-stat">
          <div class="roles-stat__value"><?= (int)$totalPermissions ?></div>
          <div class="roles-stat__label">Permissions disponibles</div>
        </div>
        <div class="roles-stat">
          <div class="roles-stat__value"><?= strtoupper($storage === 'json' ? 'JS' : ($storage === 'relational' ? 'SQL' : 'N/A')) ?></div>
          <div class="roles-stat__label">Mode de persistance</div>
        </div>
      </div>
    </div>
  </section>

  <section class="roles-grid">
    <div class="roles-panel">
      <div class="roles-panel__head">
        <div>
          <div class="roles-panel__eyebrow">Nouveau rôle</div>
          <h2 class="roles-panel__title">Créer un profil d’accès</h2>
          <p class="roles-panel__subtitle">Définissez un identifiant stable, un libellé métier et associez les permissions par module.</p>
        </div>
        <span class="roles-badge"><i class="fas fa-plus"></i> Création</span>
      </div>

      <div class="roles-panel__body">
        <form method="post" action="<?= htmlspecialchars(route_url('/roles/store')) ?>" data-role-form>
          <div class="roles-field">
            <label for="role-key-name">Clé technique</label>
            <input class="roles-input" id="role-key-name" name="key_name" placeholder="manager, support_n2, superviseur..." required>
            <div class="roles-helper">Utilisez une clé stable sans espaces pour vos contrôles d’accès.</div>
          </div>

          <div class="roles-field">
            <label for="role-label">Libellé</label>
            <input class="roles-input" id="role-label" name="label" placeholder="Responsable support, Opérateur terrain..." required>
          </div>

          <div class="roles-form-tools">
            <div class="roles-search">
              <i class="fas fa-search"></i>
              <input class="roles-input" type="search" placeholder="Filtrer une permission ou un module" data-permission-filter>
            </div>
            <div class="roles-caption">Astuce: utilisez “Tout” ou “Aucun” par module pour aller plus vite.</div>
          </div>

          <div class="roles-groups">
            <?php foreach ($permissionGroups as $groupIndex => $group): ?>
              <?php $groupPermissions = $group['permissions'] ?? []; ?>
              <?php $groupId = 'create-group-' . $groupIndex; ?>
              <section class="roles-group" data-permission-group>
                <div class="roles-group__head">
                  <div>
                    <h3 class="roles-group__title"><?= htmlspecialchars($group['label']) ?></h3>
                    <div class="roles-group__meta">
                      <span class="roles-mini-badge"><i class="fas fa-key"></i> <?= count($groupPermissions) ?> droits</span>
                    </div>
                  </div>
                  <div class="roles-group__actions">
                    <button class="roles-btn-inline" type="button" data-group-toggle="all" data-target-group="<?= htmlspecialchars($groupId) ?>">Tout</button>
                    <button class="roles-btn-inline" type="button" data-group-toggle="none" data-target-group="<?= htmlspecialchars($groupId) ?>">Aucun</button>
                  </div>
                </div>
                <div class="roles-group__body">
                  <div class="roles-permission-grid" data-group-id="<?= htmlspecialchars($groupId) ?>">
                    <?php foreach ($groupPermissions as $perm): ?>
                      <?php $permKey = (string)($perm['key_name'] ?? ''); ?>
                      <?php $scopeMeta = $permissionScopeMeta($permKey); ?>
                      <?php $permId = preg_replace('/[^a-z0-9_-]+/i', '-', strtolower($permKey)); ?>
                      <label class="roles-permission" data-permission-item data-search-text="<?= htmlspecialchars(strtolower(($group['label'] ?? '') . ' ' . ($perm['label'] ?? '') . ' ' . $permKey)) ?>">
                        <input type="checkbox" name="permissions[]" value="<?= htmlspecialchars($permKey) ?>" id="perm-<?= htmlspecialchars($permId) ?>">
                        <span class="roles-permission__card">
                          <span class="roles-permission__check"><i class="fas fa-check"></i></span>
                          <span>
                            <span class="roles-permission__topline">
                              <span class="roles-permission__title"><?= htmlspecialchars($perm['label']) ?></span>
                              <?php if ($scopeMeta): ?>
                                <span class="<?= htmlspecialchars($scopeMeta['class']) ?>"><?= htmlspecialchars($scopeMeta['label']) ?></span>
                              <?php endif; ?>
                            </span>
                            <span class="roles-permission__key"><?= htmlspecialchars($permKey) ?></span>
                          </span>
                        </span>
                      </label>
                    <?php endforeach; ?>
                  </div>
                </div>
              </section>
            <?php endforeach; ?>
          </div>

          <div class="roles-actions">
            <button class="roles-btn roles-btn--secondary" type="reset"><i class="fas fa-rotate-left"></i> Réinitialiser</button>
            <button class="roles-btn roles-btn--primary" type="submit"><i class="fas fa-plus"></i> Créer le rôle</button>
          </div>
        </form>
      </div>
    </div>

    <div class="roles-panel">
      <div class="roles-panel__head">
        <div>
          <div class="roles-panel__eyebrow">Profils existants</div>
          <h2 class="roles-panel__title">Mettre à jour les rôles</h2>
          <p class="roles-panel__subtitle">Chaque rôle expose maintenant ses permissions par module avec recherche locale et sélection rapide.</p>
        </div>
        <span class="roles-badge"><i class="fas fa-users-cog"></i> <?= count($roles) ?> rôles</span>
      </div>

      <div class="roles-panel__body">
        <?php if (empty($roles)): ?>
          <div class="roles-empty">
            <i class="fas fa-user-shield"></i>
            <p>Aucun rôle n’est encore configuré.</p>
          </div>
        <?php else: ?>
          <div class="roles-list">
            <?php foreach ($roles as $role): ?>
              <?php $selectedPermissions = $rolePerms[$role['id']] ?? []; ?>
              <?php $selectedModules = 0; ?>
              <?php foreach ($permissionGroups as $group): ?>
                <?php $groupKeys = array_map(static fn($permission): string => (string)($permission['key_name'] ?? ''), $group['permissions'] ?? []); ?>
                <?php if (!empty(array_intersect($groupKeys, $selectedPermissions))): ?>
                  <?php $selectedModules++; ?>
                <?php endif; ?>
              <?php endforeach; ?>
              <?php $previewPermissions = array_slice($selectedPermissions, 0, 4); ?>
              <article class="roles-role-card">
                <div class="roles-role-card__head">
                  <div>
                    <h3 class="roles-role-card__title"><?= htmlspecialchars($role['label']) ?></h3>
                    <div class="roles-role-card__key"><?= htmlspecialchars($role['key_name']) ?></div>
                  </div>
                  <div class="roles-role-card__actions">
                    <button
                      class="roles-btn roles-btn--ghost"
                      type="button"
                      data-open-role-view
                      data-modal-title="<?= htmlspecialchars($role['label']) ?>"
                      data-template-id="role-view-template-<?= (int)$role['id'] ?>"
                    >
                      <i class="fas fa-eye"></i> Vue
                    </button>
                    <button
                      class="roles-btn roles-btn--primary"
                      type="button"
                      data-open-role-edit
                      data-modal-title="<?= htmlspecialchars($role['label']) ?>"
                      data-template-id="role-edit-template-<?= (int)$role['id'] ?>"
                    >
                      <i class="fas fa-pen-to-square"></i> Modifier
                    </button>
                  </div>
                </div>

                <div class="roles-role-card__body">
                  <div class="roles-role-card__summary">
                    <div class="roles-role-card__meta">
                      <span class="roles-badge"><i class="fas fa-check-circle"></i> <?= count($selectedPermissions) ?> permissions</span>
                      <span class="roles-badge"><i class="fas fa-layer-group"></i> <?= $selectedModules ?> modules actifs</span>
                    </div>

                    <?php if (!empty($previewPermissions)): ?>
                      <div class="roles-role-card__preview">
                        <?php foreach ($previewPermissions as $permissionKey): ?>
                          <span class="roles-preview-chip">
                            <i class="fas fa-key"></i>
                            <?= htmlspecialchars($permissionLabelMap[$permissionKey]['label'] ?? $permissionKey) ?>
                          </span>
                        <?php endforeach; ?>
                        <?php if (count($selectedPermissions) > count($previewPermissions)): ?>
                          <span class="roles-preview-chip">+<?= count($selectedPermissions) - count($previewPermissions) ?> autres</span>
                        <?php endif; ?>
                      </div>
                    <?php else: ?>
                      <p class="roles-role-card__hint">Aucune permission spécifique n’est encore rattachée à ce rôle.</p>
                    <?php endif; ?>

                    <p class="roles-role-card__hint">Utilisez Vue pour consulter les droits par module sans encombrer la page, puis Modifier pour mettre à jour le libellé et les permissions du rôle.</p>
                  </div>
                </div>

                <template id="role-view-template-<?= (int)$role['id'] ?>">
                  <div class="roles-read-layout">
                    <div class="roles-read-summary">
                      <span class="roles-badge"><i class="fas fa-fingerprint"></i> <?= htmlspecialchars($role['key_name']) ?></span>
                      <span class="roles-badge"><i class="fas fa-check-circle"></i> <?= count($selectedPermissions) ?> permissions</span>
                      <span class="roles-badge"><i class="fas fa-layer-group"></i> <?= $selectedModules ?> modules</span>
                    </div>

                    <?php if (empty($selectedPermissions)): ?>
                      <div class="roles-read-empty">
                        <i class="fas fa-user-lock"></i>
                        <p>Ce rôle n’a aucune permission spécifique pour le moment.</p>
                      </div>
                    <?php else: ?>
                      <div class="roles-read-grid">
                        <?php foreach ($permissionGroups as $group): ?>
                          <?php $visiblePermissions = array_values(array_filter($group['permissions'] ?? [], static fn($permission): bool => in_array((string)($permission['key_name'] ?? ''), $selectedPermissions, true))); ?>
                          <?php if (empty($visiblePermissions)): ?>
                            <?php continue; ?>
                          <?php endif; ?>
                          <section class="roles-read-group">
                            <div class="roles-read-group__head">
                              <h4 class="roles-read-group__title"><?= htmlspecialchars($group['label']) ?></h4>
                              <span class="roles-mini-badge"><i class="fas fa-check"></i> <?= count($visiblePermissions) ?></span>
                            </div>
                            <div class="roles-read-list">
                              <?php foreach ($visiblePermissions as $perm): ?>
                                <?php $permKey = (string)($perm['key_name'] ?? ''); ?>
                                <?php $scopeMeta = $permissionScopeMeta($permKey); ?>
                                <div class="roles-read-item">
                                  <span class="roles-read-item__icon"><i class="fas fa-key"></i></span>
                                  <div>
                                    <div class="roles-read-item__topline">
                                      <div class="roles-read-item__title"><?= htmlspecialchars($perm['label']) ?></div>
                                      <?php if ($scopeMeta): ?>
                                        <span class="<?= htmlspecialchars($scopeMeta['class']) ?>"><?= htmlspecialchars($scopeMeta['label']) ?></span>
                                      <?php endif; ?>
                                    </div>
                                    <div class="roles-read-item__key"><?= htmlspecialchars($permKey) ?></div>
                                  </div>
                                </div>
                              <?php endforeach; ?>
                            </div>
                          </section>
                        <?php endforeach; ?>
                      </div>
                    <?php endif; ?>
                  </div>
                </template>

                <template id="role-edit-template-<?= (int)$role['id'] ?>">
                  <form method="post" action="<?= htmlspecialchars(route_url('/roles/update')) ?>" data-role-form>
                    <input type="hidden" name="role_id" value="<?= (int)$role['id'] ?>">

                    <div class="roles-read-summary" style="margin-bottom: 1rem;">
                      <span class="roles-badge"><i class="fas fa-fingerprint"></i> <?= htmlspecialchars($role['key_name']) ?></span>
                      <span class="roles-badge"><i class="fas fa-check-circle"></i> <span data-total-selected><?= count($selectedPermissions) ?></span> permissions sélectionnées</span>
                    </div>

                    <div class="roles-field">
                      <label for="role-label-<?= (int)$role['id'] ?>">Libellé</label>
                      <input class="roles-input" id="role-label-<?= (int)$role['id'] ?>" name="label" value="<?= htmlspecialchars($role['label']) ?>" required>
                    </div>

                    <div class="roles-form-tools">
                      <div class="roles-search">
                        <i class="fas fa-search"></i>
                        <input class="roles-input" type="search" placeholder="Filtrer dans ce rôle" data-permission-filter>
                      </div>
                      <div class="roles-caption">Sélectionnez uniquement les droits utiles à ce profil.</div>
                    </div>

                    <div class="roles-groups">
                      <?php foreach ($permissionGroups as $groupIndex => $group): ?>
                        <?php $groupPermissions = $group['permissions'] ?? []; ?>
                        <?php $groupId = 'role-' . (int)$role['id'] . '-group-' . $groupIndex; ?>
                        <?php $selectedInGroup = count(array_intersect(array_map(static fn($permission): string => (string)($permission['key_name'] ?? ''), $groupPermissions), $selectedPermissions)); ?>
                        <section class="roles-group" data-permission-group>
                          <div class="roles-group__head">
                            <div>
                              <h4 class="roles-group__title"><?= htmlspecialchars($group['label']) ?></h4>
                              <div class="roles-group__meta">
                                <span class="roles-mini-badge"><i class="fas fa-key"></i> <?= count($groupPermissions) ?> droits</span>
                                <span class="roles-mini-badge"><i class="fas fa-check"></i> <span data-selected-count><?= $selectedInGroup ?></span> sélectionnés</span>
                              </div>
                            </div>
                            <div class="roles-group__actions">
                              <button class="roles-btn-inline" type="button" data-group-toggle="all" data-target-group="<?= htmlspecialchars($groupId) ?>">Tout</button>
                              <button class="roles-btn-inline" type="button" data-group-toggle="none" data-target-group="<?= htmlspecialchars($groupId) ?>">Aucun</button>
                            </div>
                          </div>
                          <div class="roles-group__body">
                            <div class="roles-permission-grid" data-group-id="<?= htmlspecialchars($groupId) ?>">
                              <?php foreach ($groupPermissions as $perm): ?>
                                <?php $permKey = (string)($perm['key_name'] ?? ''); ?>
                                <?php $scopeMeta = $permissionScopeMeta($permKey); ?>
                                <?php $permId = preg_replace('/[^a-z0-9_-]+/i', '-', strtolower($permKey)); ?>
                                <label class="roles-permission" data-permission-item data-search-text="<?= htmlspecialchars(strtolower(($group['label'] ?? '') . ' ' . ($perm['label'] ?? '') . ' ' . $permKey)) ?>">
                                  <input
                                    type="checkbox"
                                    name="permissions[]"
                                    value="<?= htmlspecialchars($permKey) ?>"
                                    id="role-<?= (int)$role['id'] ?>-perm-<?= htmlspecialchars($permId) ?>"
                                    <?= in_array($permKey, $selectedPermissions, true) ? 'checked' : '' ?>
                                  >
                                  <span class="roles-permission__card">
                                    <span class="roles-permission__check"><i class="fas fa-check"></i></span>
                                    <span>
                                      <span class="roles-permission__topline">
                                        <span class="roles-permission__title"><?= htmlspecialchars($perm['label']) ?></span>
                                        <?php if ($scopeMeta): ?>
                                          <span class="<?= htmlspecialchars($scopeMeta['class']) ?>"><?= htmlspecialchars($scopeMeta['label']) ?></span>
                                        <?php endif; ?>
                                      </span>
                                      <span class="roles-permission__key"><?= htmlspecialchars($permKey) ?></span>
                                    </span>
                                  </span>
                                </label>
                              <?php endforeach; ?>
                            </div>
                          </div>
                        </section>
                      <?php endforeach; ?>
                    </div>

                    <div class="roles-actions">
                      <button class="roles-btn roles-btn--secondary" type="button" data-close-modal><i class="fas fa-xmark"></i> Fermer</button>
                      <button class="roles-btn roles-btn--primary" type="submit"><i class="fas fa-floppy-disk"></i> Mettre à jour</button>
                    </div>
                  </form>
                </template>
              </article>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </section>
</div>

<div class="roles-modal" data-modal="view" aria-hidden="true">
  <div class="roles-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="roles-view-modal-title">
    <div class="roles-modal__header">
      <div>
        <div class="roles-modal__eyebrow">Consultation</div>
        <h3 class="roles-modal__title" id="roles-view-modal-title">Permissions du rôle</h3>
        <p class="roles-modal__subtitle">Vue synthétique des droits par module.</p>
      </div>
      <button class="roles-modal__close" type="button" data-close-modal aria-label="Fermer la fenêtre"><i class="fas fa-xmark"></i></button>
    </div>
    <div class="roles-modal__body" data-modal-body="view"></div>
  </div>
</div>

<div class="roles-modal" data-modal="edit" aria-hidden="true">
  <div class="roles-modal__dialog roles-modal__dialog--wide" role="dialog" aria-modal="true" aria-labelledby="roles-edit-modal-title">
    <div class="roles-modal__header">
      <div>
        <div class="roles-modal__eyebrow">Modification</div>
        <h3 class="roles-modal__title" id="roles-edit-modal-title">Mettre à jour le rôle</h3>
        <p class="roles-modal__subtitle">Ajustez le libellé puis activez les permissions nécessaires par module.</p>
      </div>
      <button class="roles-modal__close" type="button" data-close-modal aria-label="Fermer la fenêtre"><i class="fas fa-xmark"></i></button>
    </div>
    <div class="roles-modal__body" data-modal-body="edit"></div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    var body = document.body;
    var modalRegistry = {
      view: document.querySelector('[data-modal="view"]'),
      edit: document.querySelector('[data-modal="edit"]')
    };

    var closeModal = function (modalName) {
      var modal = modalRegistry[modalName];
      if (!modal) {
        return;
      }

      modal.classList.remove('is-open');
      modal.setAttribute('aria-hidden', 'true');
      var modalBody = modal.querySelector('[data-modal-body]');
      if (modalBody) {
        modalBody.innerHTML = '';
      }

      if (!document.querySelector('.roles-modal.is-open')) {
        body.classList.remove('roles-modal-open');
      }
    };

    var updateSelectionCounters = function (form) {
      if (!form) {
        return;
      }

      var totalSelected = form.querySelectorAll('input[type="checkbox"]:checked').length;
      var totalTarget = form.querySelector('[data-total-selected]');
      if (totalTarget) {
        totalTarget.textContent = String(totalSelected);
      }

      form.querySelectorAll('[data-permission-group]').forEach(function (group) {
        var selectedInGroup = group.querySelectorAll('input[type="checkbox"]:checked').length;
        var selectedTarget = group.querySelector('[data-selected-count]');
        if (selectedTarget) {
          selectedTarget.textContent = String(selectedInGroup);
        }
      });
    };

    var initRoleForm = function (scope) {
      if (!scope || scope.dataset.roleFormReady === 'true') {
        return;
      }

      scope.dataset.roleFormReady = 'true';
      var searchInput = scope.querySelector('[data-permission-filter]');
      var groups = Array.from(scope.querySelectorAll('[data-permission-group]'));

      var applyFilter = function () {
        var query = (searchInput && searchInput.value ? searchInput.value : '').trim().toLowerCase();

        groups.forEach(function (group) {
          var hasVisibleItem = false;

          group.querySelectorAll('[data-permission-item]').forEach(function (item) {
            var haystack = item.getAttribute('data-search-text') || '';
            var visible = query === '' || haystack.indexOf(query) !== -1;
            item.dataset.hidden = visible ? 'false' : 'true';
            if (visible) {
              hasVisibleItem = true;
            }
          });

          group.dataset.hidden = hasVisibleItem ? 'false' : 'true';
        });
      };

      if (searchInput) {
        searchInput.addEventListener('input', applyFilter);
      }

      scope.querySelectorAll('[data-group-toggle]').forEach(function (button) {
        button.addEventListener('click', function () {
          var targetGroup = button.getAttribute('data-target-group');
          var mode = button.getAttribute('data-group-toggle');
          var container = scope.querySelector('[data-group-id="' + targetGroup + '"]');
          if (!container) {
            return;
          }

          container.querySelectorAll('input[type="checkbox"]').forEach(function (checkbox) {
            checkbox.checked = mode === 'all';
          });

          updateSelectionCounters(scope);
        });
      });

      scope.querySelectorAll('input[type="checkbox"]').forEach(function (checkbox) {
        checkbox.addEventListener('change', function () {
          updateSelectionCounters(scope);
        });
      });

      updateSelectionCounters(scope);
      applyFilter();
    };

    var openModalFromTemplate = function (modalName, templateId, title) {
      var modal = modalRegistry[modalName];
      var template = document.getElementById(templateId);
      if (!modal || !template) {
        return;
      }

      Object.keys(modalRegistry).forEach(function (key) {
        if (key !== modalName && modalRegistry[key] && modalRegistry[key].classList.contains('is-open')) {
          closeModal(key);
        }
      });

      var modalBody = modal.querySelector('[data-modal-body]');
      var titleNode = modal.querySelector('.roles-modal__title');

      if (titleNode && title) {
        titleNode.textContent = modalName === 'view' ? 'Permissions de ' + title : 'Modifier ' + title;
      }

      if (modalBody) {
        modalBody.innerHTML = '';
        modalBody.appendChild(template.content.cloneNode(true));
      }

      modal.classList.add('is-open');
      modal.setAttribute('aria-hidden', 'false');
      body.classList.add('roles-modal-open');

      var modalForm = modalBody ? modalBody.querySelector('[data-role-form]') : null;
      if (modalForm) {
        initRoleForm(modalForm);
      }
    };

    document.querySelectorAll('[data-role-form]').forEach(function (form) {
      initRoleForm(form);
    });

    document.querySelectorAll('[data-open-role-view]').forEach(function (button) {
      button.addEventListener('click', function () {
        openModalFromTemplate('view', button.getAttribute('data-template-id'), button.getAttribute('data-modal-title') || 'ce rôle');
      });
    });

    document.querySelectorAll('[data-open-role-edit]').forEach(function (button) {
      button.addEventListener('click', function () {
        openModalFromTemplate('edit', button.getAttribute('data-template-id'), button.getAttribute('data-modal-title') || 'ce rôle');
      });
    });

    document.addEventListener('click', function (event) {
      var closeButton = event.target.closest('[data-close-modal]');
      if (!closeButton) {
        return;
      }

      var modal = closeButton.closest('.roles-modal');
      if (modal && modal.getAttribute('data-modal')) {
        closeModal(modal.getAttribute('data-modal'));
      }
    });

    document.querySelectorAll('.roles-modal').forEach(function (modal) {
      modal.addEventListener('click', function (event) {
        if (event.target === modal && modal.getAttribute('data-modal')) {
          closeModal(modal.getAttribute('data-modal'));
        }
      });
    });

    document.addEventListener('keydown', function (event) {
      if (event.key !== 'Escape') {
        return;
      }

      Object.keys(modalRegistry).forEach(function (modalName) {
        if (modalRegistry[modalName] && modalRegistry[modalName].classList.contains('is-open')) {
          closeModal(modalName);
        }
      });
    });
  });
</script>