<div class="k-p-4">
  <ng-template appPageHeaderActions>
    <button kendoButton themeColor="primary"
      [disabled]="!selectedRole || isSuperAdminSelected || isSaving"
      (click)="save()">
      {{ isSaving ? 'Saving...' : 'Save Changes' }}
    </button>
  </ng-template>

  <p class="k-mb-4" style="color:#666">
    Choose a role, then grant Read / Write / Delete / Approve per module. Changes apply
    immediately after saving — no re-login required. <strong>super_admin</strong> always has
    full access and cannot be edited.
  </p>

  <div *ngIf="savedMessage" class="k-mb-3 k-p-2"
    style="background:#e8f5e9;border-radius:4px;color:#2e7d32">
    {{ savedMessage }}
  </div>

  <div *ngIf="isLoading" class="k-mb-3">
    <kendo-loader type="infinite-spinner"></kendo-loader> Loading...
  </div>

  <!-- Role selector -->
  <div class="grid grid-cols-1 md:grid-cols-2 gap-1 k-mb-4">
    <label class="flex flex-col gap-1">
      <span style="font-weight:600">Role</span>
      <kendo-dropdownlist
        [data]="roleNames"
        [value]="selectedRole"
        (valueChange)="selectRole($event)"
        [valuePrimitive]="true">
      </kendo-dropdownlist>
    </label>
    <div class="flex flex-col gap-1" *ngIf="selectedDescription">
      <span style="font-weight:600">Description</span>
      <span style="padding-top:6px;color:#555">{{ selectedDescription }}</span>
    </div>
  </div>

  <div *ngIf="isSuperAdminSelected" class="k-mb-3 k-p-2"
    style="background:#fff3e0;border-radius:4px;color:#e65100">
    super_admin bypasses all permission checks — every module is shown as fully granted and is read-only.
  </div>

  <!-- Module × action matrix for the selected role -->
  <kendo-grid [data]="rows" [height]="520" *ngIf="selectedRole">
    <kendo-grid-column field="module" title="Module" [width]="220"></kendo-grid-column>

    <kendo-grid-column title="Read" [width]="100">
      <ng-template kendoGridCellTemplate let-dataItem>
        <input type="checkbox" [(ngModel)]="dataItem.canRead" [disabled]="isSuperAdminSelected" />
      </ng-template>
    </kendo-grid-column>

    <kendo-grid-column title="Write" [width]="100">
      <ng-template kendoGridCellTemplate let-dataItem>
        <input type="checkbox" [(ngModel)]="dataItem.canWrite" [disabled]="isSuperAdminSelected" />
      </ng-template>
    </kendo-grid-column>

    <kendo-grid-column title="Delete" [width]="100">
      <ng-template kendoGridCellTemplate let-dataItem>
        <input type="checkbox" [(ngModel)]="dataItem.canDelete" [disabled]="isSuperAdminSelected" />
      </ng-template>
    </kendo-grid-column>

    <kendo-grid-column title="Approve" [width]="100">
      <ng-template kendoGridCellTemplate let-dataItem>
        <input type="checkbox" [(ngModel)]="dataItem.canApprove" [disabled]="isSuperAdminSelected" />
      </ng-template>
    </kendo-grid-column>
  </kendo-grid>
</div>
