<!-- eslint-disable @angular-eslint/template/cyclomatic-complexity -->
@if (isOpen() && !isThemeStudioFullscreen()) {
  <!-- Backdrop (hidden on mobile where the modal is full-screen) -->
  <div
    class="fixed inset-0 z-[90] hidden bg-black/60 backdrop-blur-sm transition-opacity duration-200 md:block"
    [class.opacity-100]="animating()"
    [class.opacity-0]="!animating()"
    (click)="onBackdropClick()"
    (keydown.enter)="onBackdropClick()"
    (keydown.space)="onBackdropClick()"
    role="button"
    tabindex="0"
    [attr.aria-label]="'settings.closeAria' | translate"
  ></div>

  <!-- Modal: full-screen page on mobile, centered dialog on desktop -->
  <div class="fixed inset-0 z-[91] flex pointer-events-none md:items-center md:justify-center md:p-4">
    <div
      appThemeNode="settingsModalSurface"
      class="pointer-events-auto relative flex h-full w-full overflow-hidden bg-card transition-all duration-200 md:h-[min(720px,88vh)] md:max-w-5xl md:rounded-lg md:border md:border-border md:shadow-lg"
      [class.scale-100]="animating()"
      [class.opacity-100]="animating()"
      [class.md:scale-95]="!animating()"
      [class.opacity-0]="!animating()"
      (click)="$event.stopPropagation()"
      (keydown.enter)="$event.stopPropagation()"
      (keydown.space)="$event.stopPropagation()"
      role="dialog"
      aria-modal="true"
      aria-labelledby="settings-modal-title"
      tabindex="-1"
    >
      <!-- Side Navigation: persistent on desktop; full-width "menu" page on mobile -->
      <nav
        appThemeNode="settingsModalNav"
        class="flex w-full flex-shrink-0 flex-col border-r border-border bg-card md:w-56"
        [class.hidden]="isMobile() && mobilePage() !== 'menu'"
      >
        <div class="flex items-center justify-between border-b border-border px-3 py-3">
          <h2
            id="settings-modal-title"
            class="text-lg font-semibold text-foreground"
          >
            {{ 'settings.title' | translate }}
          </h2>
          @if (isMobile()) {
            <button
              (click)="close()"
              type="button"
              [attr.aria-label]="'settings.closeAria' | translate"
              class="grid h-9 w-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground md:hidden"
            >
              <ng-icon
                name="lucideX"
                class="w-5 h-5"
              />
            </button>
          }
        </div>

        <div class="flex-1 overflow-y-auto py-2">
          <!-- Global section -->
          <p class="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
            {{ 'settings.sections.general' | translate }}
          </p>
          @for (page of globalPages(); track page.id) {
            <button
              (click)="navigate(page.id)"
              type="button"
              class="mx-2 flex w-[calc(100%-1rem)] items-center gap-2.5 rounded-md px-2.5 py-2.5 text-sm transition-colors md:py-1.5"
              [class.bg-secondary]="activePage() === page.id && !isMobile()"
              [class.text-foreground]="activePage() === page.id"
              [class.font-medium]="activePage() === page.id"
              [class.text-muted-foreground]="activePage() !== page.id"
              [class.hover:bg-secondary/70]="activePage() !== page.id"
              [class.hover:text-foreground]="activePage() !== page.id"
            >
              <ng-icon
                [name]="page.icon"
                class="w-4 h-4"
              />
              {{ page.label }}
            </button>
          }

          <!-- Server section -->
          @if (manageableRooms().length > 0) {
            <div class="mt-3 pt-3 border-t border-border">
              <p class="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                {{ 'settings.sections.server' | translate }}
              </p>

              <!-- Server selector -->
              <div class="px-3 pb-2">
                <select
                  class="w-full rounded-lg border border-border bg-secondary px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
                  [value]="selectedServerId() || ''"
                  (change)="onServerSelect($event)"
                >
                  <option value="">{{ 'settings.selectServer' | translate }}</option>
                  @for (room of manageableRooms(); track room.id) {
                    <option [value]="room.id">{{ room.name }}</option>
                  }
                </select>
              </div>

              @if (selectedServerId() && canAccessSelectedServer()) {
                @for (page of serverPages(); track page.id) {
                  <button
                    (click)="navigate(page.id)"
                    type="button"
                    class="mx-2 flex w-[calc(100%-1rem)] items-center gap-2.5 rounded-md px-2.5 py-2.5 text-sm transition-colors md:py-1.5"
                    [class.bg-secondary]="activePage() === page.id && !isMobile()"
                    [class.text-foreground]="activePage() === page.id"
                    [class.font-medium]="activePage() === page.id"
                    [class.text-muted-foreground]="activePage() !== page.id"
                    [class.hover:bg-secondary/70]="activePage() !== page.id"
                    [class.hover:text-foreground]="activePage() !== page.id"
                  >
                    <ng-icon
                      [name]="page.icon"
                      class="w-4 h-4"
                    />
                    {{ page.label }}
                  </button>
                }
              }
            </div>
          }
        </div>

        <div class="mt-auto border-t border-border px-3 py-3">
          <button
            type="button"
            (click)="openThirdPartyLicenses()"
            class="text-left text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline underline-offset-4"
          >
            {{ 'settings.thirdPartyLicenses.link' | translate }}
          </button>
        </div>
      </nav>

      <!-- Content: shown alongside nav on desktop; full-width "detail" page on mobile -->
      <div
        class="flex flex-1 flex-col min-w-0"
        [class.hidden]="isMobile() && mobilePage() !== 'detail'"
      >
        <!-- Header -->
        <div
          appThemeNode="settingsModalHeader"
          class="flex items-center justify-between border-b border-border px-3 py-3 flex-shrink-0 md:px-5"
        >
          <div class="flex min-w-0 items-center gap-1">
            @if (isMobile()) {
              <button
                (click)="backToMenu()"
                type="button"
                [attr.aria-label]="'settings.backToMenuAria' | translate"
                class="grid h-9 w-9 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground md:hidden"
              >
                <ng-icon
                  name="lucideChevronLeft"
                  class="w-5 h-5"
                />
              </button>
            }
            <h3 class="truncate text-lg font-semibold text-foreground">
              @switch (activePage()) {
                @case ('general') {
                  {{ 'settings.pages.general' | translate }}
                }
                @case ('plugins') {
                  {{ 'settings.pages.clientPlugins' | translate }}
                }
                @case ('network') {
                  {{ 'settings.pages.network' | translate }}
                }
                @case ('theme') {
                  {{ 'settings.pages.theme' | translate }}
                }
                @case ('notifications') {
                  {{ 'settings.pages.notifications' | translate }}
                }
                @case ('voice') {
                  {{ 'settings.pages.voice' | translate }}
                }
                @case ('updates') {
                  {{ 'settings.pages.updates' | translate }}
                }
                @case ('localApi') {
                  {{ 'settings.pages.localApi' | translate }}
                }
                @case ('data') {
                  {{ 'settings.pages.data' | translate }}
                }
                @case ('debugging') {
                  {{ 'settings.pages.debugging' | translate }}
                }
                @case ('server') {
                  {{ 'settings.pages.server' | translate }}
                }
                @case ('serverPlugins') {
                  {{ 'settings.pages.serverPlugins' | translate }}
                }
                @case ('members') {
                  {{ 'settings.pages.members' | translate }}
                }
                @case ('bans') {
                  {{ 'settings.pages.bans' | translate }}
                }
                @case ('permissions') {
                  {{ 'settings.pages.permissions' | translate }}
                }
              }
            </h3>
          </div>
          <div class="flex items-center gap-2">
            <button
              (click)="close()"
              type="button"
              [attr.aria-label]="'settings.closeAria' | translate"
              class="grid h-9 w-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
            >
              <ng-icon
                name="lucideX"
                class="w-5 h-5"
              />
            </button>
          </div>
        </div>

        <!-- Scrollable Content Area -->
        <div
          appThemeNode="settingsModalContent"
          class="flex-1 overflow-y-auto bg-background px-4 py-4 sm:px-5 sm:py-4"
        >
          @switch (activePage()) {
            @case ('general') {
              <app-general-settings />
            }
            @case ('plugins') {
              <app-plugin-manager
                scope="client"
                (closed)="navigate('general')"
                (storeOpened)="closeForExternalNavigation()"
              />
            }
            @case ('network') {
              <app-network-settings />
            }
            @case ('theme') {
              <div class="max-w-3xl space-y-5">
                <div class="flex flex-wrap items-start justify-between gap-4">
                  <div>
                    <p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">{{ 'settings.theme.activeTheme' | translate }}</p>
                    <h4 class="mt-2 text-lg font-semibold text-foreground">{{ activeThemeName() }}</h4>
                    <p class="mt-2 max-w-2xl text-sm text-muted-foreground">
                      {{ 'settings.theme.description' | translate }}
                    </p>
                  </div>

                  @if (themeStudioMinimized()) {
                    <span class="rounded-full bg-primary/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-primary">{{
                      'settings.theme.minimized' | translate
                    }}</span>
                  }
                </div>

                @if (savedThemesAvailable()) {
                  <div class="space-y-2">
                    <label
                      for="settings-saved-theme-select"
                      class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground"
                    >
                      {{ 'settings.theme.savedTheme' | translate }}
                    </label>

                    <div class="flex flex-wrap gap-2">
                      <select
                        id="settings-saved-theme-select"
                        class="min-w-[16rem] flex-1 rounded-lg border border-border bg-secondary px-3 py-2 text-sm text-foreground outline-none transition-colors focus:border-primary/40 focus:ring-1 focus:ring-primary"
                        [value]="selectedSavedTheme()?.fileName || ''"
                        [disabled]="savedThemesBusy() && savedThemes().length === 0"
                        (change)="onSavedThemeSelect($event)"
                      >
                        <option value="">
                          {{
                            savedThemes().length > 0 ? ('settings.theme.chooseSavedTheme' | translate) : ('settings.theme.noSavedThemes' | translate)
                          }}
                        </option>
                        @for (savedTheme of savedThemes(); track savedTheme.fileName) {
                          <option
                            [value]="savedTheme.fileName"
                            [disabled]="!savedTheme.isValid"
                          >
                            {{ savedTheme.themeName }}
                          </option>
                        }
                      </select>

                      <button
                        type="button"
                        (click)="editSelectedSavedTheme()"
                        [disabled]="!selectedSavedTheme()?.isValid || (savedThemesBusy() && savedThemes().length === 0)"
                        class="inline-flex items-center rounded-lg border border-border bg-secondary px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-secondary/80 disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        {{ 'settings.theme.editInStudio' | translate }}
                      </button>
                    </div>
                  </div>
                }

                <div class="flex flex-wrap gap-2">
                  <button
                    type="button"
                    (click)="openThemeStudio()"
                    class="inline-flex items-center rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
                  >
                    {{ themeStudioMinimized() ? ('settings.theme.reopenStudio' | translate) : ('settings.theme.openStudio' | translate) }}
                  </button>

                  <button
                    type="button"
                    (click)="restoreDefaultTheme()"
                    class="inline-flex items-center rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-sm font-medium text-destructive transition-colors hover:bg-destructive/15"
                  >
                    {{ 'settings.theme.restoreDefault' | translate }}
                  </button>
                </div>
              </div>
            }
            @case ('notifications') {
              <app-notifications-settings />
            }
            @case ('voice') {
              <app-voice-settings />
            }
            @case ('updates') {
              <app-updates-settings />
            }
            @case ('localApi') {
              <app-local-api-settings />
            }
            @case ('data') {
              @defer {
                <app-data-settings />
              } @loading {
                <section class="rounded-lg border border-border bg-card/60 p-5">
                  <p class="text-sm text-muted-foreground">{{ 'settings.dataLoading' | translate }}</p>
                </section>
              }
            }
            @case ('debugging') {
              <app-debugging-settings />
            }
            @case ('server') {
              <app-server-settings
                [server]="selectedServer()"
                [isAdmin]="canManageSelectedServerSettings()"
                [canManageIcon]="canManageSelectedServerIcon()"
                [canDeleteServer]="isSelectedServerOwner()"
              />
            }
            @case ('serverPlugins') {
              @if (currentRoom()) {
                <app-plugin-manager
                  scope="server"
                  (closed)="navigate('server')"
                  (storeOpened)="closeForExternalNavigation()"
                />
              } @else {
                <section class="rounded-lg border border-border bg-card p-5">
                  <h4 class="text-sm font-semibold text-foreground">{{ 'settings.serverPlugins.title' | translate }}</h4>
                  <p class="mt-2 text-sm text-muted-foreground">
                    {{
                      'settings.serverPlugins.description'
                        | translate: { serverName: selectedServer()?.name || ('settings.serverPlugins.thisServer' | translate) }
                    }}
                  </p>
                </section>
              }
            }
            @case ('members') {
              <app-members-settings
                [server]="selectedServer()"
                [isAdmin]="canManageSelectedMembers()"
                [accessRole]="selectedServerRole()"
              />
            }
            @case ('bans') {
              <app-bans-settings
                [server]="selectedServer()"
                [isAdmin]="canManageSelectedBans()"
              />
            }
            @case ('permissions') {
              <app-permissions-settings
                #permissionsComp
                [server]="selectedServer()"
                [isAdmin]="canManageSelectedPermissions()"
              />
            }
          }
        </div>
      </div>

      @if (showThirdPartyLicenses()) {
        <div
          class="absolute inset-0 z-10 bg-background/70 backdrop-blur-sm"
          (click)="closeThirdPartyLicenses()"
          (keydown.enter)="closeThirdPartyLicenses()"
          (keydown.space)="closeThirdPartyLicenses()"
          role="button"
          tabindex="0"
          [attr.aria-label]="'settings.thirdPartyLicenses.closeAria' | translate"
        ></div>

        <div class="pointer-events-none absolute inset-0 z-[11] flex justify-center p-4 sm:p-6">
          <div
            class="pointer-events-auto flex min-h-0 w-full max-w-2xl self-stretch flex-col overflow-hidden rounded-lg border border-border bg-card shadow-lg"
          >
            <div class="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
              <div>
                <h4 class="text-base font-semibold text-foreground">{{ 'settings.thirdPartyLicenses.title' | translate }}</h4>
                <p class="mt-1 text-sm text-muted-foreground">{{ 'settings.thirdPartyLicenses.description' | translate }}</p>
              </div>

              <button
                type="button"
                (click)="closeThirdPartyLicenses()"
                class="grid h-9 w-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
                [attr.aria-label]="'settings.thirdPartyLicenses.closeAria' | translate"
              >
                <ng-icon
                  name="lucideX"
                  class="w-5 h-5"
                />
              </button>
            </div>

            <div class="min-h-0 flex-1 overflow-y-auto px-5 py-4 space-y-4">
              @for (license of thirdPartyLicenses; track license.id) {
                <section class="rounded-lg border border-border bg-secondary/20 p-4">
                  <div class="flex items-start justify-between gap-4">
                    <div>
                      <h5 class="text-sm font-semibold text-foreground">{{ license.name }}</h5>
                      <p class="text-xs text-muted-foreground">{{ license.licenseName }}</p>
                    </div>

                    <a
                      [href]="license.sourceUrl"
                      target="_blank"
                      rel="noopener noreferrer"
                      class="text-xs font-medium text-primary hover:underline underline-offset-4"
                    >
                      {{ 'settings.thirdPartyLicenses.viewLicense' | translate }}
                    </a>
                  </div>

                  <div class="mt-4 rounded-md bg-background/80 px-3 py-3">
                    <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                      {{ 'settings.thirdPartyLicenses.packages' | translate }}
                    </p>
                    <div class="mt-3 flex flex-wrap gap-2">
                      @for (packageName of license.packages; track packageName) {
                        <span class="rounded-full border border-border bg-card px-2.5 py-1 text-[11px] font-medium leading-4 text-foreground">
                          {{ packageName }}
                        </span>
                      }
                    </div>

                    @if (license.note) {
                      <p class="mt-3 text-xs leading-5 text-muted-foreground">{{ license.note }}</p>
                    }

                    <div class="mt-4">
                      <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                        {{ 'settings.thirdPartyLicenses.licenseText' | translate }}
                      </p>
                      <pre
                        class="mt-2 whitespace-pre-wrap break-words rounded-md border border-border/70 bg-card px-3 py-3 text-[11px] leading-5 text-muted-foreground"
                        >{{ license.text }}</pre
                      >
                    </div>
                  </div>
                </section>
              }
            </div>
          </div>
        </div>
      }
    </div>
  </div>
}
