<ng-container *transloco="let t; prefix: 'settingsAuth'">
<div class="main-container">
  <div class="settings-header">
    <h2 class="settings-title">
      <i class="pi pi-key"></i>
      {{ t('title') }}
    </h2>
    <p class="settings-description">
      {{ t('description') }}
    </p>
  </div>

  <div class="settings-card">
    <div class="section-header">
      <h3 class="section-title">
        <i class="pi pi-shield"></i>
        {{ t('methods.sectionTitle') }}
      </h3>
      <p class="section-description">
        {{ t('methods.sectionDesc') }}
      </p>
    </div>

    <div class="section-body">
      <div class="auth-methods-list">
        <div class="auth-method-item is-active is-locked">
          <div class="auth-method-content">
            <div class="auth-method-header">
              <div class="auth-method-icon">
                <i class="pi pi-user"></i>
              </div>
              <div class="auth-method-info">
                <span class="auth-method-label">{{ t('internal.label') }}</span>
                <span class="auth-method-status active">{{ t('internal.status') }}</span>
              </div>
            </div>
            <p class="auth-method-description">
              {{ t('internal.description') }}
            </p>
          </div>
          <p-checkbox
            [(ngModel)]="internalAuthEnabled"
            [binary]="true"
            [disabled]="true">
          </p-checkbox>
        </div>

        <div class="auth-method-item" [class.is-active]="oidcEnabled">
          <div class="auth-method-content">
            <div class="auth-method-header">
              <div class="auth-method-icon oidc">
                <i class="pi pi-key"></i>
              </div>
              <div class="auth-method-info">
                <span class="auth-method-label">
                  {{ t('oidc.label') }}
                </span>
                <span class="auth-method-status" [class.active]="oidcEnabled">
                  {{ oidcEnabled ? t('oidc.enabled') : t('oidc.disabled') }}
                </span>
              </div>
            </div>
            <p class="auth-method-description">
              {{ t('oidc.description') }}
              <app-external-doc-link docType="authentication"></app-external-doc-link>
              @if (!isOidcFormComplete() && !oidcEnabled) {
                <span class="config-hint">{{ t('oidc.configHint') }}</span>
              }
            </p>
          </div>
          <p-toggleswitch
            [(ngModel)]="oidcEnabled"
            [disabled]="!isOidcFormComplete()"
            (onChange)="toggleOidcEnabled()">
          </p-toggleswitch>
        </div>
      </div>
    </div>
  </div>

  <div class="settings-card">
    <div class="section-header">
      <h3 class="section-title">
        <i class="pi pi-cog"></i>
        {{ t('providerConfig.sectionTitle') }}
      </h3>
      <p class="section-description">
        {{ t('providerConfig.sectionDesc') }}
      </p>
    </div>

    <div class="section-body">
      <div class="config-grid">
        <div class="config-item">
          <label for="providerName">{{ t('providerConfig.providerName') }}</label>
          <input
            pInputText
            pSize="small"
            id="providerName"
            [(ngModel)]="oidcProvider.providerName"
            [placeholder]="t('providerConfig.providerPlaceholder')"/>
        </div>

        <div class="config-item">
          <label for="clientId">{{ t('providerConfig.clientId') }}</label>
          <input
            pInputText
            pSize="small"
            id="clientId"
            [(ngModel)]="oidcProvider.clientId"
            [placeholder]="t('providerConfig.clientIdPlaceholder')"/>
        </div>

        <div class="config-item">
          <label for="clientSecret">{{ t('providerConfig.clientSecret') }}</label>
          <input
            pInputText
            pSize="small"
            id="clientSecret"
            type="password"
            [(ngModel)]="oidcProvider.clientSecret"
            [placeholder]="t('providerConfig.clientSecretPlaceholder')"/>
          <span class="field-hint">{{ t('providerConfig.clientSecretHint') }}</span>
        </div>

        <div class="config-item span-2">
          <label for="issuerUri">{{ t('providerConfig.issuerUri') }}</label>
          <input
            pInputText
            pSize="small"
            id="issuerUri"
            [(ngModel)]="oidcProvider.issuerUri"
            [placeholder]="t('providerConfig.issuerPlaceholder')"/>
        </div>

        <div class="config-item">
          <label for="scopes">{{ t('providerConfig.scope') }}</label>
          <input
            pInputText
            pSize="small"
            id="scopes"
            [(ngModel)]="oidcProvider.scopes"
            [placeholder]="'openid profile email groups offline_access'"/>
          <span class="field-hint">{{ t('providerConfig.scopeHint') }}</span>
        </div>
      </div>

      @if (oidcEnabled) {
        <div class="config-grid" style="margin-top: 0.75rem;">
          <div class="config-item">
            <label for="sessionDuration">{{ t('providerConfig.sessionDuration') }}</label>
            <p-inputNumber
              size="small"
              inputId="sessionDuration"
              [(ngModel)]="sessionDurationHours"
              [min]="1"
              [max]="8760"
              [showButtons]="true"
              [placeholder]="t('providerConfig.sessionDurationPlaceholder')"
              mode="decimal"
              [useGrouping]="false">
            </p-inputNumber>
            <span class="field-hint">{{ t('providerConfig.sessionDurationHint') }}</span>
          </div>
        </div>
      }

      <div class="claims-section">
        <h4 class="subsection-title">{{ t('providerConfig.claimMappings') }}</h4>
        <p class="subsection-description">
          {{ t('providerConfig.claimDesc') }}
        </p>
        <div class="claims-grid">
          <div class="config-item">
            <label for="claimUsername">{{ t('providerConfig.usernameClaim') }}</label>
            <input
              pInputText
              pSize="small"
              id="claimUsername"
              [(ngModel)]="oidcProvider.claimMapping.username"
              [placeholder]="t('providerConfig.usernamePlaceholder')"/>
          </div>
          <div class="config-item">
            <label for="claimEmail">{{ t('providerConfig.emailClaim') }}</label>
            <input
              pInputText
              pSize="small"
              id="claimEmail"
              [(ngModel)]="oidcProvider.claimMapping.email"
              [placeholder]="t('providerConfig.emailPlaceholder')"/>
          </div>
          <div class="config-item">
            <label for="claimName">{{ t('providerConfig.nameClaim') }}</label>
            <input
              pInputText
              pSize="small"
              id="claimName"
              [(ngModel)]="oidcProvider.claimMapping.name"
              [placeholder]="t('providerConfig.namePlaceholder')"/>
          </div>
          <div class="config-item">
            <label for="claimGroups">{{ t('providerConfig.groupsClaim') }}</label>
            <input
              pInputText
              pSize="small"
              id="claimGroups"
              [(ngModel)]="oidcProvider.claimMapping.groups"
              [placeholder]="t('providerConfig.groupsPlaceholder')"/>
          </div>
        </div>
      </div>

      <div class="provider-actions-row">
        <div class="test-results-inline">
          @if (testConnectionResult) {
            <div class="test-results-toggle"
                 [style.border-radius]="showTestDetails ? '6px 6px 0 0' : '6px'"
                 (click)="showTestDetails = !showTestDetails">
              @if (testConnectionResult.success) {
                <i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
                <span>{{ t('testConnection.passed') }}</span>
              } @else {
                <i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
                <span>{{ t('testConnection.failed') }}</span>
              }
              <span style="color: var(--p-text-muted-color); font-size: 0.75rem;">
                ({{ testConnectionResult.checks.length }} {{ t('testConnection.checks') }})
              </span>
              <i class="pi pi-chevron-right toggle-chevron" [class.expanded]="showTestDetails"></i>
            </div>
          }
        </div>
        <div class="provider-action-buttons">
          <p-button
            [outlined]="true"
            [label]="t('testConnection.button')"
            [icon]="isTestingConnection ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
            severity="info"
            size="small"
            (click)="testConnection()"
            [disabled]="!oidcProvider.issuerUri || isTestingConnection">
          </p-button>
          <p-button
            [outlined]="true"
            [label]="'common.save' | transloco"
            icon="pi pi-save"
            severity="success"
            size="small"
            (click)="saveOidcProvider()"
            [disabled]="!isOidcFormComplete()">
          </p-button>
        </div>
      </div>
      @if (testConnectionResult && showTestDetails) {
        <div class="test-results-details">
          @for (check of testConnectionResult.checks; track check.name) {
            <div class="test-check-row">
              @switch (check.status) {
                @case ('PASS') {
                  <i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
                }
                @case ('FAIL') {
                  <i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
                }
                @case ('WARN') {
                  <i class="pi pi-exclamation-triangle" style="color: var(--p-yellow-500);"></i>
                }
                @case ('SKIP') {
                  <i class="pi pi-minus-circle" style="color: var(--p-surface-400);"></i>
                }
              }
              <span class="check-name">{{ check.name }}</span>
              <span class="check-message">{{ check.message }}</span>
            </div>
          }
        </div>
      }
    </div>
  </div>

  <div class="settings-card">
    <div class="section-header">
      <h3 class="section-title">
        <i class="pi pi-info-circle"></i>
        {{ t('infoPanel.sectionTitle') }}
      </h3>
      <p class="section-description">
        {{ t('infoPanel.sectionDesc') }}
      </p>
    </div>
    <div class="section-body">
      <div class="info-panel-grid">
        @for (item of infoItems; track item.labelKey) {
          <div class="info-panel-item">
            <span class="info-panel-label">{{ t(item.labelKey) }}</span>
            <div class="info-panel-value-row">
              <code class="info-panel-value">{{ item.value }}</code>
              <p-button
                [outlined]="true"
                icon="pi pi-copy"
                severity="secondary"
                size="small"
                [style]="{'min-width': '2rem'}"
                (click)="copyToClipboard(item.value)">
              </p-button>
            </div>
          </div>
        }
      </div>
    </div>
  </div>

  @if (oidcEnabled) {
    <div class="settings-card">
      <div class="section-header">
        <h3 class="section-title">
          <i class="pi pi-ban"></i>
          {{ t('oidcOnly.sectionTitle') }}
        </h3>
        <p class="section-description">
          {{ t('oidcOnly.sectionDesc') }}
        </p>
      </div>

      <div class="section-body">
        <div class="provisioning-toggle">
          <div class="toggle-content">
            <div class="toggle-info">
              <span class="toggle-label">{{ t('oidcOnly.label') }}</span>
              <span class="toggle-status" [class.active]="oidcForceOnlyMode">
                {{ oidcForceOnlyMode ? t('oidcOnly.enabled') : t('oidcOnly.disabled') }}
              </span>
            </div>
            <p class="toggle-description">
              {{ t('oidcOnly.description') }}
            </p>
            @if (oidcForceOnlyMode) {
              <p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
                <i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
                {{ t('oidcOnly.backdoorHint') }}
              </p>
            }
          </div>
          <p-toggleswitch
            [(ngModel)]="oidcForceOnlyMode"
            (onChange)="toggleOidcForceOnlyMode()">
          </p-toggleswitch>
        </div>
      </div>
    </div>

    <div class="settings-card">
      <div class="section-header">
        <div class="section-header-row">
          <div class="section-header-text">
            <h3 class="section-title">
              <i class="pi pi-users"></i>
              {{ t('provisioning.sectionTitle') }}
            </h3>
            <p class="section-description">
              {{ t('provisioning.sectionDesc') }}
            </p>
          </div>
        </div>
      </div>

      <div class="section-body">
        <div class="provisioning-toggle">
          <div class="toggle-content">
            <div class="toggle-info">
              <span class="toggle-label">{{ t('provisioning.autoLabel') }}</span>
              <span class="toggle-status" [class.active]="autoUserProvisioningEnabled">
                {{ autoUserProvisioningEnabled ? t('provisioning.autoEnabled') : t('provisioning.autoDisabled') }}
              </span>
            </div>
            <p class="toggle-description">
              {{ t('provisioning.autoDesc') }}
            </p>
          </div>
          <p-toggleswitch
            [(ngModel)]="autoUserProvisioningEnabled"
            inputId="autoProvision"
            (onChange)="saveOidcAutoProvisionSettings()">
          </p-toggleswitch>
        </div>

        <div class="provisioning-toggle">
          <div class="toggle-content">
            <div class="toggle-info">
              <span class="toggle-label">{{ t('provisioning.linkLocalLabel') }}</span>
              <span class="toggle-status" [class.active]="allowLocalAccountLinking">
                {{ allowLocalAccountLinking ? t('provisioning.autoEnabled') : t('provisioning.autoDisabled') }}
              </span>
            </div>
            <p class="toggle-description">
              {{ t('provisioning.linkLocalDesc') }}
            </p>
            @if (allowLocalAccountLinking) {
              <p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
                <i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
                {{ t('provisioning.linkLocalWarning') }}
              </p>
            }
          </div>
          <p-toggleswitch
            [(ngModel)]="allowLocalAccountLinking"
            inputId="linkLocal"
            (onChange)="saveOidcAutoProvisionSettings()">
          </p-toggleswitch>
        </div>

        @if (autoUserProvisioningEnabled) {
          <div class="default-settings">
            <div class="permissions-group">
              <h4 class="group-title">{{ t('provisioning.defaultPerms') }}</h4>
              <div class="permissions-grid">
                <div class="permission-item">
                  <p-checkbox
                    [binary]="true"
                    [disabled]="true"
                    [ngModel]="true"
                    inputId="permissionRead">
                  </p-checkbox>
                  <label for="permissionRead">{{ t('provisioning.readBooks') }}</label>
                </div>
                @for (perm of availablePermissions; track perm) {
                  <div class="permission-item">
                    <p-checkbox
                      [(ngModel)]="perm.selected"
                      [binary]="true"
                      [inputId]="perm.value">
                    </p-checkbox>
                    <label [for]="perm.value">{{ t(perm.translationKey) }}</label>
                  </div>
                }
              </div>
            </div>

            <div class="libraries-group">
              <h4 class="group-title">{{ t('provisioning.defaultLibraryAccess') }}</h4>
              <div style="display: flex; align-items: center; gap: 0.5rem; justify-content: space-between;">
                <p-multiSelect
                  [options]="allLibraries"
                  optionLabel="name"
                  optionValue="id"
                  [(ngModel)]="editingLibraryIds"
                  [placeholder]="t('provisioning.selectLibraries')"
                  appendTo="body"
                  class="libraries-select"
                  style="flex: 1;">
                </p-multiSelect>
                <p-button
                  icon="pi pi-save"
                  [label]="'common.save' | transloco"
                  [outlined]="true"
                  severity="success"
                  size="small"
                  (click)="saveOidcAutoProvisionSettings()">
                </p-button>
              </div>
            </div>

          </div>
        }
      </div>
    </div>

    <div class="settings-card">
      <div class="section-header">
        <div class="section-header-row">
          <div class="section-header-text">
            <h3 class="section-title">
              <i class="pi pi-sitemap"></i>
              {{ t('groupMapping.sectionTitle') }}
            </h3>
            <p class="section-description">
              {{ t('groupMapping.sectionDesc') }}
            </p>
          </div>
          <p-button
            icon="pi pi-plus"
            [label]="t('groupMapping.addMapping')"
            [outlined]="true"
            severity="success"
            size="small"
            (click)="openNewGroupMapping()">
          </p-button>
        </div>
      </div>

      <div class="section-body">
        <div class="config-grid-2col" style="margin-bottom: 1rem;">
          <div class="config-item">
            <label for="groupSyncMode">{{ t('groupMapping.syncModeLabel') }}</label>
            <p-select
              inputId="groupSyncMode"
              [(ngModel)]="groupSyncMode"
              [options]="groupSyncModeOptions"
              optionLabel="label"
              optionValue="value"
              appendTo="body">
            </p-select>
            <span class="field-hint">{{ t('groupMapping.syncModeHint') }}</span>
          </div>
          <div class="config-item" style="display: flex; align-items: flex-end;">
            <p-button
              [outlined]="true"
              [label]="'common.save' | transloco"
              icon="pi pi-save"
              severity="success"
              size="small"
              (click)="saveGroupSyncMode()">
            </p-button>
          </div>
        </div>

        @if (groupMappings.length > 0) {
          <p-table [value]="groupMappings" [tableStyle]="{'min-width': '100%'}" styleClass="p-datatable-sm">
            <ng-template #header>
              <tr>
                <th>{{ t('groupMapping.colGroupClaim') }}</th>
                <th>{{ t('groupMapping.colAdmin') }}</th>
                <th>{{ t('groupMapping.colPermissions') }}</th>
                <th>{{ t('groupMapping.colLibraries') }}</th>
                <th>{{ t('groupMapping.colDescription') }}</th>
                <th style="width: 8rem;"></th>
              </tr>
            </ng-template>
            <ng-template #body let-mapping>
              <tr>
                <td>{{ mapping.oidcGroupClaim }}</td>
                <td>
                  @if (mapping.isAdmin) {
                    <app-tag [rounded]="true" color="warning" size="2xs">Admin</app-tag>
                  }
                </td>
                <td>
                  @for (perm of mapping.permissions; track perm) {
                    <app-tag [rounded]="true" color="info" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ perm }}</app-tag>
                  }
                </td>
                <td>
                  @for (libId of mapping.libraryIds; track libId) {
                    <app-tag [rounded]="true" color="secondary" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ getLibraryName(libId) }}</app-tag>
                  }
                </td>
                <td>{{ mapping.description }}</td>
                <td>
                  <div style="display: flex; gap: 0.5rem;">
                    <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (click)="openEditGroupMapping(mapping)"></p-button>
                    <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (click)="deleteGroupMapping(mapping)"></p-button>
                  </div>
                </td>
              </tr>
            </ng-template>
          </p-table>
        }
      </div>
    </div>

    <p-dialog
      [header]="editingGroupMapping.id ? t('groupMapping.editTitle') : t('groupMapping.addTitle')"
      [(visible)]="showGroupMappingDialog"
      [modal]="true"
      [style]="{width: '550px', maxWidth: '95vw'}"
      [dismissableMask]="true">
      <div class="config-grid" style="gap: 1rem;">
        <div class="config-item full-width">
          <label for="gmGroupClaim">{{ t('groupMapping.groupClaimLabel') }}</label>
          <input pInputText id="gmGroupClaim" [(ngModel)]="editingGroupMapping.oidcGroupClaim" [placeholder]="t('groupMapping.groupClaimPlaceholder')"/>
        </div>
        <div class="config-item full-width">
          <label for="gmDescription">{{ t('groupMapping.descriptionLabel') }}</label>
          <input pInputText id="gmDescription" [(ngModel)]="editingGroupMapping.description" [placeholder]="t('groupMapping.descriptionPlaceholder')"/>
        </div>
        <div class="config-item full-width">
          <div class="provisioning-toggle" style="padding: 0;">
            <div class="toggle-content">
              <span class="toggle-label">{{ t('groupMapping.adminLabel') }}</span>
            </div>
            <p-toggleswitch [(ngModel)]="editingGroupMapping.isAdmin"></p-toggleswitch>
          </div>
        </div>
        <div class="config-item full-width">
          <h4 class="group-title">{{ t('groupMapping.permissionsLabel') }}</h4>
          <div class="permissions-grid">
            <div class="permission-item">
              <p-checkbox [binary]="true" [disabled]="true" [ngModel]="true" inputId="gmPermRead"></p-checkbox>
              <label for="gmPermRead">{{ t('provisioning.readBooks') }}</label>
            </div>
            @for (perm of editingGroupMappingPerms; track perm) {
              <div class="permission-item">
                <p-checkbox [(ngModel)]="perm.selected" [binary]="true" [inputId]="'gm_' + perm.value"></p-checkbox>
                <label [for]="'gm_' + perm.value">{{ t(perm.translationKey) }}</label>
              </div>
            }
          </div>
        </div>
        <div class="config-item full-width">
          <h4 class="group-title">{{ t('groupMapping.librariesLabel') }}</h4>
          <p-multiSelect
            [options]="allLibraries"
            optionLabel="name"
            optionValue="id"
            [(ngModel)]="editingGroupMappingLibraryIds"
            [placeholder]="t('provisioning.selectLibraries')"
            appendTo="body"
            class="libraries-select">
          </p-multiSelect>
        </div>
      </div>
      <ng-template #footer>
        <p-button
          [label]="'common.save' | transloco"
          icon="pi pi-check"
          (click)="saveGroupMapping()"
          [disabled]="!editingGroupMapping.oidcGroupClaim">
        </p-button>
      </ng-template>
    </p-dialog>
  }
</div>
</ng-container>
