<p-confirmdialog />

<app-admin-page-frame [breadcrumbItems]="breadcrumbItems()">
    <div class="admin-status">
        @if (isSettingsPage()) {
        <div class="mb-4 grid overflow-hidden rounded-lg border border-surface-100 bg-[var(--p-content-background)] dark:border-surface-800 md:grid-cols-4">
            <div class="flex min-w-0 items-baseline gap-2 border-b border-surface-100 px-4 py-3 dark:border-surface-800 md:border-r md:border-b-0">
                <span class="text-lg leading-none font-bold text-[var(--p-text-color)]">{{ users().length | number }}</span>
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.tabs.users" | transloco }}</span>
            </div>
            <div class="flex min-w-0 items-baseline gap-2 border-b border-surface-100 px-4 py-3 dark:border-surface-800 md:border-r md:border-b-0">
                <span class="text-lg leading-none font-bold text-[var(--p-text-color)]">{{ instanceAdmins() | number }}</span>
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.roles.instanceAdmin" | transloco }}</span>
            </div>
            <div class="flex min-w-0 items-baseline gap-2 border-b border-surface-100 px-4 py-3 dark:border-surface-800 md:border-r md:border-b-0">
                <span class="text-lg leading-none font-bold text-[var(--p-text-color)]">{{ totalSites() | number }}</span>
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.tabs.sites" | transloco }}</span>
            </div>
            <div class="flex min-w-0 items-baseline gap-2 px-4 py-3">
                <span class="text-lg leading-none font-bold text-[var(--p-text-color)]">{{ activeTeams() | number }}</span>
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.tabs.teams" | transloco }}</span>
            </div>
        </div>

        <p-tabs [(value)]="activeSettingsTab" class="hk-admin-tabs">
            <p-tablist>
                <p-tab value="users">{{ "admin.tabs.users" | transloco }}</p-tab>
                <p-tab value="sites">{{ "admin.tabs.sites" | transloco }}</p-tab>
                <p-tab value="teams">{{ "admin.tabs.teams" | transloco }}</p-tab>
                <p-tab value="globalFilters">{{ "admin.tabs.globalFilters" | transloco }}</p-tab>
            </p-tablist>

            <p-tabpanels>
                <p-tabpanel value="users">
                    <section class="admin-panel admin-panel--wide admin-panel--table" aria-labelledby="settings-users-title">
                        <div class="admin-panel__header">
                            <div class="admin-panel__title-block">
                                <h2 id="settings-users-title">{{ "admin.users.title" | transloco }}</h2>
                                <span class="admin-panel__meta">{{ users().length | number }} {{ "admin.tabs.users" | transloco }}</span>
                            </div>
                            <p-iconfield class="admin-search">
                                <p-inputicon class="pi pi-search" />
                                <input pInputText #settingsUsersSearch [placeholder]="'common.searchPlaceholder' | transloco" (input)="settingsUsersTable.filterGlobal($any($event.target).value, 'contains')" />
                            </p-iconfield>
                        </div>

                        @if (deleteUserBlock() || userMfaStatus() || userActionStatus()) {
                        <div class="admin-panel__messages">
                            @if (deleteUserBlock()) {
                            <p-message severity="warn" styleClass="w-full" [text]="deleteUserBlockMessage()" />
                            } @if (userMfaStatus(); as status) {
                            <p-message [severity]="status.severity" styleClass="w-full" [text]="userMfaStatusMessage()" />
                            } @if (userActionStatus(); as status) {
                            <p-message [severity]="status.severity" styleClass="w-full" [text]="userActionStatusMessage()" />
                            }
                        </div>
                        }

                        <div class="admin-table-wrap">
                            <p-table
                                #settingsUsersTable
                                [value]="users()"
                                [loading]="isLoading()"
                                [globalFilterFields]="['email', 'instance_role', 'created_at']"
                                [sortField]="'created_at'"
                                [sortOrder]="-1"
                                [paginator]="true"
                                [rows]="10"
                                [rowsPerPageOptions]="[10, 25, 50]"
                                [rowHover]="true"
                                responsiveLayout="scroll"
                                styleClass="p-datatable-sm admin-data-table"
                                [tableStyle]="{ 'min-width': '760px' }"
                            >
                                <ng-template pTemplate="header">
                                    <tr>
                                        <th pSortableColumn="email">{{ "common.columns.email" | transloco }}<p-sortIcon field="email" /></th>
                                        <th pSortableColumn="instance_role">{{ "common.columns.role" | transloco }}<p-sortIcon field="instance_role" /></th>
                                        <th pSortableColumn="created_at">{{ "common.columns.created" | transloco }}<p-sortIcon field="created_at" /></th>
                                        <th>{{ "common.columns.actions" | transloco }}</th>
                                    </tr>
                                </ng-template>
                                <ng-template pTemplate="body" let-user>
                                    <tr>
                                        <td>
                                            <div class="admin-user-cell">
                                                <span>{{ user.email }}</span>
                                                @if (isInstanceOwner(user)) {
                                                <span class="hk-owner-chip">{{ "admin.roles.instanceOwner" | transloco }}</span>
                                                }
                                            </div>
                                        </td>
                                        <td>
                                            <p-select [options]="roleOptions()" [formControl]="roleControl(user.id)" (onChange)="onRoleChange(user, $event.value)" optionLabel="label" optionValue="value" class="admin-role-select" appendTo="body" />
                                        </td>
                                        <td><app-relative-date-time [value]="user.created_at" /></td>
                                        <td>
                                            <app-table-row-actions [items]="userActions(user)" [loading]="isDisablingUser(user) || isDeletingUser(user)" />
                                        </td>
                                    </tr>
                                </ng-template>
                            </p-table>
                        </div>
                    </section>
                </p-tabpanel>

                <p-tabpanel value="sites">
                    <section class="admin-panel admin-panel--wide admin-panel--table" aria-labelledby="settings-sites-title">
                        <div class="admin-panel__header">
                            <div class="admin-panel__title-block">
                                <h2 id="settings-sites-title">{{ "admin.sites.title" | transloco }}</h2>
                                <span class="admin-panel__meta">{{ sites().length | number }} {{ "admin.tabs.sites" | transloco }}</span>
                            </div>
                            <p-iconfield class="admin-search">
                                <p-inputicon class="pi pi-search" />
                                <input pInputText #settingsSitesSearch [placeholder]="'common.searchPlaceholder' | transloco" (input)="settingsSitesTable.filterGlobal($any($event.target).value, 'contains')" />
                            </p-iconfield>
                        </div>
                        @if (siteActionStatus(); as status) {
                        <div class="admin-panel__messages">
                            <p-message [severity]="status.severity" styleClass="w-full" [text]="siteActionStatusMessage()" />
                        </div>
                        }
                        <div class="admin-table-wrap">
                            <p-table
                                #settingsSitesTable
                                [value]="sites()"
                                [loading]="isLoadingSites()"
                                [globalFilterFields]="['domain', 'owner_email', 'created_at']"
                                [sortField]="'created_at'"
                                [sortOrder]="-1"
                                [paginator]="true"
                                [rows]="10"
                                [rowsPerPageOptions]="[10, 25, 50]"
                                [rowHover]="true"
                                responsiveLayout="scroll"
                                styleClass="p-datatable-sm admin-data-table"
                                [tableStyle]="{ 'min-width': '760px' }"
                            >
                                <ng-template pTemplate="header">
                                    <tr>
                                        <th pSortableColumn="domain">{{ "common.columns.domain" | transloco }}<p-sortIcon field="domain" /></th>
                                        <th pSortableColumn="owner_email">{{ "common.columns.owner" | transloco }}<p-sortIcon field="owner_email" /></th>
                                        <th pSortableColumn="created_at">{{ "common.columns.created" | transloco }}<p-sortIcon field="created_at" /></th>
                                        <th>{{ "common.columns.actions" | transloco }}</th>
                                    </tr>
                                </ng-template>
                                <ng-template pTemplate="body" let-site>
                                    <tr>
                                        <td><a [href]="'https://' + site.domain" target="_blank" rel="noopener" class="admin-link">{{ site.domain }}</a></td>
                                        <td>{{ siteOwnerEmail(site) }}</td>
                                        <td><app-relative-date-time [value]="site.created_at" /></td>
                                        <td>
                                            <app-table-row-actions [items]="siteActions(site)" [loading]="isDeletingSite(site)" />
                                        </td>
                                    </tr>
                                </ng-template>
                            </p-table>
                        </div>
                    </section>
                </p-tabpanel>

                <p-tabpanel value="teams">
                    <section class="admin-panel admin-panel--wide admin-panel--table" aria-labelledby="settings-teams-title">
                        <div class="admin-panel__header">
                            <div class="admin-panel__title-block">
                                <h2 id="settings-teams-title">{{ "admin.teams.title" | transloco }}</h2>
                                <span class="admin-panel__meta">{{ teams().length | number }} {{ "admin.tabs.teams" | transloco }}</span>
                            </div>
                            <p-iconfield class="admin-search">
                                <p-inputicon class="pi pi-search" />
                                <input pInputText #settingsTeamsSearch [placeholder]="'common.searchPlaceholder' | transloco" (input)="settingsTeamsTable.filterGlobal($any($event.target).value, 'contains')" />
                            </p-iconfield>
                        </div>
                        @if (teamActionStatus(); as status) {
                        <div class="admin-panel__messages">
                            <p-message [severity]="status.severity" styleClass="w-full" [text]="teamActionStatusMessage()" />
                        </div>
                        }
                        <div class="admin-table-wrap">
                            <p-table
                                #settingsTeamsTable
                                [value]="teams()"
                                [loading]="isLoadingTeams()"
                                [globalFilterFields]="['name', 'created_at']"
                                [sortField]="'created_at'"
                                [sortOrder]="-1"
                                [paginator]="true"
                                [rows]="10"
                                [rowsPerPageOptions]="[10, 25, 50]"
                                [rowHover]="true"
                                responsiveLayout="scroll"
                                styleClass="p-datatable-sm admin-data-table"
                                [tableStyle]="{ 'min-width': '820px' }"
                            >
                                <ng-template pTemplate="header">
                                    <tr>
                                        <th pSortableColumn="name">{{ "common.columns.name" | transloco }}<p-sortIcon field="name" /></th>
                                        <th pSortableColumn="member_count">{{ "common.columns.members" | transloco }}<p-sortIcon field="member_count" /></th>
                                        <th pSortableColumn="site_count">{{ "common.columns.sites" | transloco }}<p-sortIcon field="site_count" /></th>
                                        <th pSortableColumn="is_archived">{{ "common.columns.status" | transloco }}<p-sortIcon field="is_archived" /></th>
                                        <th>{{ "common.columns.actions" | transloco }}</th>
                                    </tr>
                                </ng-template>
                                <ng-template pTemplate="body" let-team>
                                    <tr>
                                        <td>{{ team.name }}</td>
                                        <td>{{ team.member_count }}</td>
                                        <td>{{ team.site_count }}</td>
                                        <td>
                                            @if (team.is_default) {
                                            <p-tag [value]="'admin.teams.status.default' | transloco" severity="info" />
                                            } @else if (team.is_archived) {
                                            <p-tag [value]="'admin.teams.status.archived' | transloco" severity="warn" />
                                            } @else {
                                            <p-tag [value]="'admin.teams.status.active' | transloco" severity="success" />
                                            }
                                        </td>
                                        <td>
                                            <app-table-row-actions [items]="teamActions(team)" [loading]="isDeletingTeam(team)" />
                                        </td>
                                    </tr>
                                </ng-template>
                            </p-table>
                        </div>
                    </section>
                </p-tabpanel>

                <p-tabpanel value="globalFilters">
                    @if (activeSettingsTab() === "globalFilters") {
                    <section class="admin-panel admin-panel--wide admin-panel--form" aria-labelledby="settings-filters-title">
                        <div class="admin-panel__header">
                            <div class="admin-panel__title-block">
                                <h2 id="settings-filters-title">{{ "admin.exclusions.title" | transloco }}</h2>
                            </div>
                        </div>
                        <div class="admin-panel__content">
                            <app-admin-global-exclusion-settings />
                        </div>
                    </section>
                    }
                </p-tabpanel>
            </p-tabpanels>
        </p-tabs>
        } @else {
        <div class="mb-4 grid overflow-hidden rounded-lg border border-surface-100 bg-[var(--p-content-background)] dark:border-surface-800 lg:grid-cols-[minmax(0,1.15fr)_repeat(3,minmax(0,0.95fr))]">
            <div class="flex min-w-0 items-center justify-between gap-3 border-b border-surface-100 px-4 py-3 dark:border-surface-800 lg:border-r lg:border-b-0">
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.health.title" | transloco }}</span>
                <p-tag [value]="runtimeStatusKey() | transloco" [severity]="runtimeStatusSeverity()" />
            </div>
            <div class="flex min-w-0 items-center justify-between gap-3 border-b border-surface-100 px-4 py-3 dark:border-surface-800 lg:border-r lg:border-b-0">
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.overview.version" | transloco }}</span>
                <span class="truncate font-bold text-[var(--p-text-color)]">{{ systemInfo()?.version || "-" }}</span>
            </div>
            <div class="flex min-w-0 items-center justify-between gap-3 border-b border-surface-100 px-4 py-3 dark:border-surface-800 lg:border-r lg:border-b-0">
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.ingest.hits" | transloco }}</span>
                <span class="truncate font-bold text-[var(--p-text-color)]">{{ recentHits() | number }}</span>
            </div>
            <div class="flex min-w-0 items-center justify-between gap-3 px-4 py-3">
                <span class="truncate text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.storage.diskUsage" | transloco }}</span>
                <span class="truncate font-bold text-[var(--p-text-color)]">{{ diskUsedPercent() }}%</span>
            </div>
        </div>

        <p-tabs [(value)]="activeAdminTab" class="hk-admin-tabs">
            <p-tablist>
                <p-tab value="runtime">{{ "admin.system.console.tabs.runtime" | transloco }}</p-tab>
                <p-tab value="operations">{{ "admin.system.console.tabs.operations" | transloco }}</p-tab>
                @if (canViewActivation()) {
                <p-tab value="activation">{{ "admin.system.console.tabs.activation" | transloco }}</p-tab>
                }
                <p-tab value="audit">{{ "admin.system.console.tabs.audit" | transloco }}</p-tab>
            </p-tablist>

            <p-tabpanels>
                <p-tabpanel value="runtime">
                    <div class="admin-status__panel-grid admin-status__panel-grid--runtime">
                        <app-system-status-card
                            titleId="runtime-health-title"
                            [title]="'admin.system.health.title' | transloco"
                            [wide]="true"
                            [loading]="isLoadingHealth()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemHealth()"
                        >
                            @if (isManagedCloud()) {
                            <a system-status-card-header class="admin-link" href="https://status.hitkeep.com" target="_blank" rel="noopener">
                                <i class="pi pi-circle-fill text-xs" aria-hidden="true"></i>
                                <span>{{ "admin.system.console.cloudStatus" | transloco }}</span>
                                <i class="pi pi-external-link" aria-hidden="true"></i>
                            </a>
                            } @if (systemHealth(); as health) {
                            <div class="admin-health-grid">
                                <div class="admin-health-tile">
                                    <span>{{ "admin.system.health.status" | transloco }}</span>
                                    <p-tag [value]="health.status" [severity]="statusSeverity(health.status)" />
                                </div>
                                <div class="admin-health-tile">
                                    <span>{{ "admin.system.health.database" | transloco }}</span>
                                    <p-tag [value]="health.database" [severity]="statusSeverity(health.database)" />
                                </div>
                                <div class="admin-health-tile">
                                    <span>{{ "admin.system.health.workers" | transloco }}</span>
                                    <p-tag [value]="health.workers" [severity]="statusSeverity(health.workers)" />
                                </div>
                                <div class="admin-health-tile">
                                    <span>{{ "admin.system.health.isLeader" | transloco }}</span>
                                    <p-tag [value]="health.is_leader ? ('admin.system.console.leader' | transloco) : ('admin.system.console.follower' | transloco)" [severity]="health.is_leader ? 'info' : 'warn'" />
                                </div>
                            </div>
                            } @else if (isLoadingHealth()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            } @else {
                            <p-message severity="error" [text]="'admin.system.console.loadFailed' | transloco" styleClass="w-full" />
                            }
                            <p system-status-card-footer class="m-0 border-t border-surface-100 px-4 py-3 text-xs text-muted-color dark:border-surface-800">
                                {{ "admin.system.health.ip2locationAttribution" | transloco }}
                                <a class="admin-link" href="https://www.ip2location.com" target="_blank" rel="noopener">IP2Location</a>
                            </p>
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-search-console-title"
                            [title]="'admin.system.searchConsole.title' | transloco"
                            [loading]="isLoadingSearchConsole()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            [metricLabel]="'admin.system.searchConsole.issues' | transloco"
                            [metricValue]="searchConsoleSyncIssueMetric()"
                            (refreshClicked)="loadSearchConsoleStatus()"
                        >
                            @if (systemSearchConsole(); as searchConsole) {
                            <p-tag system-status-card-status [value]="'admin.system.searchConsole.status.' + searchConsole.status | transloco" [severity]="statusSeverity(searchConsole.status)" />
                            } @if (systemSearchConsole(); as searchConsole) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.searchConsole.credentials" | transloco }}</dt>
                                    <dd>
                                        <p-tag [value]="'admin.system.searchConsole.credentialsStatus.' + searchConsole.credentials_status | transloco" [severity]="statusSeverity(searchConsole.credentials_status)" />
                                    </dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.searchConsole.worker" | transloco }}</dt>
                                    <dd><p-tag [value]="'admin.system.searchConsole.workerStatus.' + searchConsole.worker_status | transloco" [severity]="statusSeverity(searchConsole.worker_status)" /></dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.searchConsole.sync" | transloco }}</dt>
                                    <dd><p-tag [value]="'admin.system.searchConsole.syncStatus.' + searchConsole.sync_status | transloco" [severity]="statusSeverity(searchConsole.sync_status)" /></dd>
                                </div>
                                @if (searchConsole.last_attempt_at) {
                                <div>
                                    <dt>{{ "admin.system.searchConsole.lastAttempt" | transloco }}</dt>
                                    <dd><app-relative-date-time [value]="searchConsole.last_attempt_at" /></dd>
                                </div>
                                } @if (searchConsole.last_success_at) {
                                <div>
                                    <dt>{{ "admin.system.searchConsole.lastSuccess" | transloco }}</dt>
                                    <dd><app-relative-date-time [value]="searchConsole.last_success_at" /></dd>
                                </div>
                                } @if (searchConsole.next_retry_at) {
                                <div>
                                    <dt>{{ "admin.system.searchConsole.nextRetry" | transloco }}</dt>
                                    <dd><app-relative-date-time [value]="searchConsole.next_retry_at" /></dd>
                                </div>
                                }
                            </dl>
                            <div class="admin-metric-grid admin-metric-grid--compact">
                                <div class="admin-metric">
                                    <span>{{ "admin.system.searchConsole.connectedTeams" | transloco }}</span>
                                    <strong>{{ searchConsole.connected_teams | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.searchConsole.mappedSites" | transloco }}</span>
                                    <strong>{{ searchConsole.mapped_sites | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.searchConsole.inFlight" | transloco }}</span>
                                    <strong>{{ searchConsole.pending_syncs + searchConsole.running_syncs | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.searchConsole.issues" | transloco }}</span>
                                    <strong>{{ searchConsoleSyncIssueCount() | number }}</strong>
                                </div>
                            </div>
                            } @else if (isLoadingSearchConsole()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            } @else {
                            <p-message severity="error" [text]="'admin.system.console.loadFailed' | transloco" styleClass="w-full" />
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-ai-title"
                            [title]="'admin.system.ai.title' | transloco"
                            [loading]="isLoadingAIStatus()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            [metricLabel]="'admin.system.ai.tokens' | transloco"
                            [metricValue]="aiTokenUsageMetric()"
                            (refreshClicked)="loadSystemAIStatus()"
                        >
                            @if (systemAIStatus(); as ai) {
                            <p-tag system-status-card-status [value]="'admin.system.ai.status.' + ai.status | transloco" [severity]="statusSeverity(ai.status)" />
                            } @if (systemAIStatus(); as ai) {
                            <div
                                class="grid min-w-0 items-center gap-3 rounded-lg border border-surface-100 bg-surface-50 p-3 dark:border-surface-800 dark:bg-surface-800 md:grid-cols-[minmax(0,1fr)_auto]"
                                [class.border-red-300]="ai.budget_exhausted || ai.status === 'needs_attention'"
                                [class.dark:border-red-700]="ai.budget_exhausted || ai.status === 'needs_attention'"
                            >
                                <div class="grid min-w-0 gap-1">
                                    <span class="text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.ai.configuration" | transloco }}</span>
                                    <strong class="truncate text-base font-bold text-[var(--p-text-color)]">{{ aiProviderModelLabel() }}</strong>
                                    <small class="text-sm font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.ai.summary." + aiSummaryKey() | transloco }}</small>
                                </div>
                                <div class="flex flex-wrap justify-start gap-2 md:justify-end" [attr.aria-label]="'admin.system.ai.readiness' | transloco">
                                    <p-tag [value]="ai.enabled ? ('admin.system.ai.enabled' | transloco) : ('admin.system.ai.disabled' | transloco)" [severity]="ai.enabled ? 'success' : 'secondary'" />
                                    <p-tag [value]="ai.configured ? ('admin.system.ai.configured' | transloco) : ('admin.system.ai.notConfigured' | transloco)" [severity]="ai.configured ? 'success' : 'warn'" />
                                </div>
                            </div>

                            <div class="mt-3 grid gap-3 md:grid-cols-2">
                                <div class="grid min-w-0 gap-2 rounded-lg border border-surface-100 p-3 dark:border-surface-800">
                                    <div class="flex min-w-0 items-baseline justify-between gap-3">
                                        <span class="text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.ai.requests" | transloco }}</span>
                                        <strong class="truncate text-base font-bold text-[var(--p-text-color)]">{{ aiRequestUsageMetric() }}</strong>
                                    </div>
                                    <div class="h-2 overflow-hidden rounded-full bg-surface-100 dark:bg-surface-700" aria-hidden="true">
                                        <span class="block h-full rounded-full bg-primary" [style.width.%]="aiRequestBudgetPercent()"></span>
                                    </div>
                                    <small class="truncate text-xs font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.ai.budgetWindow" | transloco }}: {{ formatMinutes(ai.budget_window_minutes) }}</small>
                                </div>
                                <div class="grid min-w-0 gap-2 rounded-lg border border-surface-100 p-3 dark:border-surface-800">
                                    <div class="flex min-w-0 items-baseline justify-between gap-3">
                                        <span class="text-xs font-bold uppercase text-[var(--p-text-muted-color)]">{{ "admin.system.ai.tokens" | transloco }}</span>
                                        <strong class="truncate text-base font-bold text-[var(--p-text-color)]">{{ aiTokenUsageMetric() }}</strong>
                                    </div>
                                    <div class="h-2 overflow-hidden rounded-full bg-surface-100 dark:bg-surface-700" aria-hidden="true">
                                        <span class="block h-full rounded-full bg-primary" [style.width.%]="aiTokenBudgetPercent()"></span>
                                    </div>
                                    <small class="truncate text-xs font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.ai.budgetWindow" | transloco }}: {{ formatMinutes(ai.budget_window_minutes) }}</small>
                                </div>
                            </div>

                            <dl class="admin-definition-list admin-definition-list--compact mt-4">
                                <div>
                                    <dt>{{ "admin.system.ai.configMode" | transloco }}</dt>
                                    <dd>{{ "admin.system.ai.configModes." + ai.config_mode | transloco }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.ai.provider" | transloco }}</dt>
                                    <dd>{{ ai.provider || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.ai.model" | transloco }}</dt>
                                    <dd>{{ ai.model || "-" }}</dd>
                                </div>
                                @if (ai.last_attempt_at) {
                                <div>
                                    <dt>{{ "admin.system.ai.lastAttempt" | transloco }}</dt>
                                    <dd><app-relative-date-time [value]="ai.last_attempt_at" /></dd>
                                </div>
                                } @if (ai.last_success_at) {
                                <div>
                                    <dt>{{ "admin.system.ai.lastSuccess" | transloco }}</dt>
                                    <dd><app-relative-date-time [value]="ai.last_success_at" /></dd>
                                </div>
                                } @if (ai.last_error_category) {
                                <div>
                                    <dt>{{ "admin.system.ai.lastError" | transloco }}</dt>
                                    <dd>{{ ai.last_error_category }}</dd>
                                </div>
                                }
                            </dl>
                            } @else if (isLoadingAIStatus()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            } @else {
                            <p-message severity="error" [text]="'admin.system.console.loadFailed' | transloco" styleClass="w-full" />
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-overview-title"
                            [title]="'admin.system.overview.title' | transloco"
                            [loading]="isLoadingSystem()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemInfo()"
                        >
                            @if (systemInfo(); as info) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.overview.version" | transloco }}</dt>
                                    <dd>{{ info.version || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.overview.uptime" | transloco }}</dt>
                                    <dd>{{ info.uptime || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.overview.runtimeMode" | transloco }}</dt>
                                    <dd>{{ info.runtime_mode || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.overview.publicUrl" | transloco }}</dt>
                                    <dd class="admin-mono" [pTooltip]="info.public_url" tooltipPosition="top">{{ info.public_url || "-" }}</dd>
                                </div>
                            </dl>
                            } @else if (isLoadingSystem()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-features-title"
                            [title]="'admin.system.overview.enabledFeatures' | transloco"
                            [loading]="isLoadingSystem()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemInfo()"
                        >
                            <div class="admin-feature-list">
                                @for (feature of enabledFeatureRows(); track feature.label) {
                                <div class="admin-feature">
                                    <span class="min-w-0 font-semibold">
                                        <span class="text-sm text-[var(--p-text-color)] [overflow-wrap:anywhere]">{{ feature.label }}</span>
                                        @if (feature.detail) {
                                        <br />
                                        <small class="text-sm text-[var(--p-text-muted-color)] [overflow-wrap:anywhere]">{{ feature.detail }}</small>
                                        }
                                    </span>
                                    <p-tag [value]="feature.value" [severity]="feature.enabled ? 'success' : 'secondary'" />
                                </div>
                                } @empty {
                                <div class="text-sm text-[var(--p-text-muted-color)]">{{ "admin.system.console.noFeatures" | transloco }}</div>
                                }
                            </div>
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-storage-title"
                            [title]="'admin.system.storage.title' | transloco"
                            [wide]="true"
                            [loading]="isLoadingStorage()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            [metricLabel]="'admin.system.storage.diskUsage' | transloco"
                            [metricValue]="diskUsedPercent() + '%'"
                            (refreshClicked)="loadSystemStorage()"
                        >
                            @if (systemStorage(); as storage) {
                            <div class="grid gap-4 min-[1181px]:grid-cols-[minmax(18rem,0.8fr)_minmax(0,1.2fr)]">
                                <dl class="admin-definition-list admin-definition-list--compact">
                                    <div>
                                        <dt>{{ "admin.system.storage.sharedDb" | transloco }}</dt>
                                        <dd class="admin-mono" [pTooltip]="storage.shared_db_path" tooltipPosition="top">{{ storage.shared_db_path }}</dd>
                                    </div>
                                    <div>
                                        <dt>{{ "admin.system.storage.sharedDbSize" | transloco }}</dt>
                                        <dd>{{ formatBytesValue(storage.shared_db_bytes) }}</dd>
                                    </div>
                                    <div>
                                        <dt>{{ "admin.system.storage.dataPath" | transloco }}</dt>
                                        <dd class="admin-mono" [pTooltip]="storage.data_path" tooltipPosition="top">{{ storage.data_path }}</dd>
                                    </div>
                                    <div>
                                        <dt>{{ "admin.system.storage.diskAvailable" | transloco }}</dt>
                                        <dd>{{ formatBytesValue(storage.disk_available_bytes) }} / {{ formatBytesValue(storage.disk_total_bytes) }}</dd>
                                    </div>
                                </dl>

                                <div class="admin-table-wrap">
                                    <p-table [value]="storage.tenant_dbs ?? []" [rowHover]="true" styleClass="p-datatable-sm admin-data-table">
                                        <ng-template pTemplate="header">
                                            <tr>
                                                <th>{{ "admin.system.storage.columns.tenant" | transloco }}</th>
                                                <th>{{ "admin.system.storage.columns.size" | transloco }}</th>
                                                <th>{{ "admin.system.storage.columns.path" | transloco }}</th>
                                            </tr>
                                        </ng-template>
                                        <ng-template pTemplate="body" let-db>
                                            <tr>
                                                <td>{{ db.name }}</td>
                                                <td>{{ formatBytesValue(db.bytes) }}</td>
                                                <td class="admin-mono admin-path-cell" [pTooltip]="db.path" tooltipPosition="top">{{ db.path }}</td>
                                            </tr>
                                        </ng-template>
                                        <ng-template pTemplate="emptymessage">
                                            <tr>
                                                <td colspan="3" class="admin-empty-cell">{{ "admin.system.console.noTenantDbs" | transloco }}</td>
                                            </tr>
                                        </ng-template>
                                    </p-table>
                                </div>
                            </div>
                            } @else if (isLoadingStorage()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-ingest-title"
                            [title]="'admin.system.ingest.title' | transloco"
                            [loading]="isLoadingIngest()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemIngest()"
                        >
                            @if (systemIngest(); as ingest) {
                            <div class="admin-metric-grid">
                                <div class="admin-metric">
                                    <span>{{ "admin.system.ingest.hits" | transloco }}</span>
                                    <strong>{{ ingest.recent_hits | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.ingest.events" | transloco }}</span>
                                    <strong>{{ ingest.recent_events | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.ingest.rejections" | transloco }}</span>
                                    <strong>{{ ingest.recent_rejections | number }}</strong>
                                </div>
                                <div class="admin-metric">
                                    <span>{{ "admin.system.ingest.spam" | transloco }}</span>
                                    <strong>{{ ingest.recent_spam | number }}</strong>
                                </div>
                            </div>
                            } @else if (isLoadingIngest()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="runtime-caches-title"
                            [title]="'admin.system.caches.title' | transloco"
                            [loading]="isLoadingCaches()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemCaches()"
                        >
                            @if (systemCaches(); as caches) {
                            <p-tag system-status-card-status [value]="'admin.system.caches.status.' + caches.status | transloco" [severity]="statusSeverity(caches.status)" />
                            } @if (isLoadingCaches() && !systemCaches()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            } @else {
                            <div class="admin-table-wrap">
                                <p-table [value]="cacheRows()" [rowHover]="true" styleClass="p-datatable-sm admin-data-table">
                                    <ng-template pTemplate="header">
                                        <tr>
                                            <th>{{ "admin.system.caches.columns.cache" | transloco }}</th>
                                            <th>{{ "admin.system.caches.columns.size" | transloco }}</th>
                                            <th>{{ "admin.system.caches.columns.maxSize" | transloco }}</th>
                                            <th>{{ "admin.system.caches.columns.ttl" | transloco }}</th>
                                            <th>{{ "admin.system.console.pressure" | transloco }}</th>
                                        </tr>
                                    </ng-template>
                                    <ng-template pTemplate="body" let-row>
                                        <tr>
                                            <td>{{ row.name }}</td>
                                            <td>{{ row.size | number }}</td>
                                            <td>{{ row.maxSize | number }}</td>
                                            <td>{{ row.ttl }}</td>
                                            <td>{{ row.pressure }}%</td>
                                        </tr>
                                    </ng-template>
                                </p-table>
                            </div>
                            }
                        </app-system-status-card>
                    </div>
                </p-tabpanel>

                <p-tabpanel value="operations">
                    @if (activeAdminTab() === "operations") {
                    <div class="admin-status__panel-grid admin-status__panel-grid--operations">
                        <app-system-status-card
                            titleId="operations-backups-title"
                            [title]="'admin.system.backups.title' | transloco"
                            [loading]="isLoadingBackups()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemBackups()"
                        >
                            @if (systemBackups(); as backups) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.backups.enabled" | transloco }}</dt>
                                    <dd><p-tag [value]="backups.enabled ? ('common.yes' | transloco) : ('common.no' | transloco)" [severity]="backups.enabled ? 'success' : 'warn'" /></dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.backups.configPath" | transloco }}</dt>
                                    <dd class="admin-mono" [pTooltip]="backups.config_path" tooltipPosition="top">{{ backups.config_path || ("admin.system.backups.disabled" | transloco) }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.backups.interval" | transloco }}</dt>
                                    <dd>{{ formatMinutes(backups.interval_min) }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.backups.retention" | transloco }}</dt>
                                    <dd>{{ backups.retention }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.backups.lastBackup" | transloco }}</dt>
                                    <dd>
                                        @if (backups.last_backup) {
                                        <app-relative-date-time [value]="backups.last_backup" />
                                        } @else { - }
                                    </dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.backups.recentFailures" | transloco }}</dt>
                                    <dd>{{ backups.recent_failures }}</dd>
                                </div>
                            </dl>
                            @if (backups.last_error) {
                            <p-message severity="error" styleClass="w-full mt-3" [text]="backups.last_error" />
                            } } @else if (isLoadingBackups()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="operations-spam-title"
                            [title]="'admin.system.spam.title' | transloco"
                            [loading]="isLoadingSpam()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            [actionLabel]="canRunMaintenance() ? ('admin.system.spam.actions.refresh' | transloco) : ''"
                            actionIcon="pi pi-sync"
                            [actionLoading]="isRefreshingSpam()"
                            (refreshClicked)="loadSystemSpam()"
                            (actionClicked)="refreshSpamFilter()"
                        >
                            @if (systemSpam(); as spam) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.spam.ruleCount" | transloco }}</dt>
                                    <dd>{{ spam.rule_count | number }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.spam.autoUpdate" | transloco }}</dt>
                                    <dd><p-tag [value]="spam.auto_update ? ('common.yes' | transloco) : ('common.no' | transloco)" [severity]="spam.auto_update ? 'success' : 'warn'" /></dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.spam.lastRefresh" | transloco }}</dt>
                                    <dd>
                                        @if (spam.last_refresh) {
                                        <app-relative-date-time [value]="spam.last_refresh" />
                                        } @else { - }
                                    </dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.spam.dbPath" | transloco }}</dt>
                                    <dd class="admin-mono" [pTooltip]="spam.db_path" tooltipPosition="top">{{ spam.db_path }}</dd>
                                </div>
                            </dl>
                            @if (spam.last_error) {
                            <p-message severity="error" styleClass="w-full mt-3" [text]="spam.last_error" />
                            } @if (spamActionStatus(); as status) {
                            <p-message [severity]="status.severity" styleClass="w-full mt-3" [text]="spamActionStatusMessage()" />
                            } } @else if (isLoadingSpam()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="operations-import-cleanup-title"
                            [title]="'admin.system.importCleanup.title' | transloco"
                            [loading]="isLoadingImportCleanup()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            [metricLabel]="'admin.system.importCleanup.staleBytes' | transloco"
                            [metricValue]="formatBytesValue(systemImportCleanup()?.stale_bytes ?? 0)"
                            [actionLabel]="canRunMaintenance() ? ('admin.system.importCleanup.actions.run' | transloco) : ''"
                            actionIcon="pi pi-eraser"
                            actionSeverity="warn"
                            [actionLoading]="isRunningImportCleanup()"
                            [actionDisabled]="importCleanupActionDisabled()"
                            (refreshClicked)="loadImportStageCleanup()"
                            (actionClicked)="runImportStageCleanup()"
                        >
                            @if (systemImportCleanup(); as cleanup) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.importCleanup.enabled" | transloco }}</dt>
                                    <dd><p-tag [value]="cleanup.enabled ? ('common.yes' | transloco) : ('common.no' | transloco)" [severity]="cleanup.enabled ? 'success' : 'warn'" /></dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.importCleanup.retention" | transloco }}</dt>
                                    <dd>{{ cleanup.retention_days | number }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.importCleanup.staleImports" | transloco }}</dt>
                                    <dd>{{ cleanup.stale_imports | number }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.importCleanup.staleFiles" | transloco }}</dt>
                                    <dd>{{ cleanup.stale_files | number }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.importCleanup.lastRun" | transloco }}</dt>
                                    <dd>
                                        @if (cleanup.last_run) {
                                        <app-relative-date-time [value]="cleanup.last_run" />
                                        } @else { - }
                                    </dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.importCleanup.lastCleaned" | transloco }}</dt>
                                    <dd>{{ cleanup.last_cleaned_files | number }} / {{ formatBytesValue(cleanup.last_cleaned_bytes) }}</dd>
                                </div>
                            </dl>
                            @if (cleanup.last_error) {
                            <p-message severity="error" styleClass="w-full mt-3" [text]="cleanup.last_error" />
                            } @if (importCleanupActionStatus(); as status) {
                            <p-message [severity]="status.severity" styleClass="w-full mt-3" [text]="importCleanupActionStatusMessage()" />
                            } } @else if (isLoadingImportCleanup()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>

                        <app-system-status-card
                            titleId="operations-mail-title"
                            [title]="'admin.system.mail.title' | transloco"
                            [wide]="true"
                            [loading]="isLoadingMail()"
                            [refreshLabel]="'admin.system.console.refreshCard' | transloco"
                            (refreshClicked)="loadSystemMail()"
                        >
                            @if (systemMail(); as mail) {
                            <dl class="admin-definition-list">
                                <div>
                                    <dt>{{ "admin.system.mail.configured" | transloco }}</dt>
                                    <dd><p-tag [value]="mail.configured ? ('common.yes' | transloco) : ('common.no' | transloco)" [severity]="mail.configured ? 'success' : 'warn'" /></dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.mail.driver" | transloco }}</dt>
                                    <dd>{{ mail.driver || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.mail.host" | transloco }}</dt>
                                    <dd>
                                        <span>{{ mail.host || "-" }}</span>
                                        @if (mail.port) {
                                        <span>:{{ mail.port }}</span>
                                        }
                                    </dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.mail.encryption" | transloco }}</dt>
                                    <dd>{{ mail.encryption || "-" }}</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.mail.fromAddress" | transloco }}</dt>
                                    <dd>{{ mail.from_name }} &lt;{{ mail.from_address }}&gt;</dd>
                                </div>
                                <div>
                                    <dt>{{ "admin.system.mail.passwordSet" | transloco }}</dt>
                                    <dd><p-tag [value]="mail.password_set ? ('common.yes' | transloco) : ('common.no' | transloco)" [severity]="mail.password_set ? 'success' : 'warn'" /></dd>
                                </div>
                                @if (mail.last_test_at) {
                                <div>
                                    <dt>{{ "admin.system.mail.lastTest" | transloco }}</dt>
                                    <dd>
                                        <app-relative-date-time [value]="mail.last_test_at" />
                                        @if (mail.last_test_ok !== undefined) {
                                        <p-tag [value]="mail.last_test_ok ? ('admin.system.audit.outcome.success' | transloco) : ('admin.system.audit.outcome.failure' | transloco)" [severity]="mail.last_test_ok ? 'success' : 'danger'" />
                                        }
                                    </dd>
                                </div>
                                }
                            </dl>
                            @if (mailTestResult(); as result) {
                            <p-message [severity]="result.severity" styleClass="w-full mt-3" [text]="result.message" />
                            } @if (canRunMaintenance() && mail.configured) {
                            <div system-status-card-footer class="admin-mail-test">
                                <div class="admin-mail-test__field">
                                    <label for="admin-mail-test-recipient">{{ "admin.system.mail.recipientLabel" | transloco }}</label>
                                    <input
                                        pInputText
                                        id="admin-mail-test-recipient"
                                        type="email"
                                        inputmode="email"
                                        autocomplete="email"
                                        [formControl]="mailTestRecipient"
                                        [placeholder]="'admin.system.mail.recipientPlaceholder' | transloco"
                                        [class.ng-invalid]="mailTestRecipient.touched && mailTestRecipient.invalid"
                                        [class.ng-dirty]="mailTestRecipient.dirty"
                                    />
                                    @if (mailTestRecipient.touched && mailTestRecipient.invalid) {
                                    <small>{{ "admin.system.mail.recipientInvalid" | transloco }}</small>
                                    }
                                </div>
                                <p-button
                                    icon="pi pi-send"
                                    [label]="'admin.system.mail.actions.test' | transloco"
                                    severity="secondary"
                                    size="small"
                                    (onClick)="testMail()"
                                    [loading]="isTestingMail()"
                                    [disabled]="mailTestRecipient.invalid || isTestingMail()"
                                />
                            </div>
                            } } @else if (isLoadingMail()) {
                            <div class="admin-loading"><i class="pi pi-spin pi-spinner" aria-hidden="true"></i>{{ "common.loading" | transloco }}</div>
                            }
                        </app-system-status-card>
                    </div>
                    }
                </p-tabpanel>

                <p-tabpanel value="activation">
                    @if (activeAdminTab() === "activation" && canViewActivation()) {
                    <section class="admin-panel admin-panel--wide admin-panel--table" aria-labelledby="activation-title">
                        <div class="admin-panel__header admin-panel__header--stacked">
                            <div class="admin-panel__title-block">
                                <h2 id="activation-title">{{ "admin.system.activation.title" | transloco }}</h2>
                                <span class="admin-panel__meta">{{ "admin.system.activation.subtitle" | transloco }}</span>
                            </div>
                            <div class="flex min-w-0 flex-wrap justify-end gap-2">
                                <p-select [options]="activationStatusOptions()" [formControl]="activationStatusControl" optionLabel="label" optionValue="value" size="small" appendTo="body" />
                                <p-iconfield class="admin-search">
                                    <p-inputicon class="pi pi-users" />
                                    <input
                                        pInputText
                                        [placeholder]="'admin.system.activation.filters.team' | transloco"
                                        [value]="activationTeamFilter()"
                                        (input)="activationTeamFilter.set($any($event.target).value)"
                                        (keydown.enter)="applyActivationFilters()"
                                    />
                                </p-iconfield>
                                <p-iconfield class="admin-search">
                                    <p-inputicon class="pi pi-globe" />
                                    <input
                                        pInputText
                                        [placeholder]="'admin.system.activation.filters.domain' | transloco"
                                        [value]="activationDomainFilter()"
                                        (input)="activationDomainFilter.set($any($event.target).value)"
                                        (keydown.enter)="applyActivationFilters()"
                                    />
                                </p-iconfield>
                                <p-button icon="pi pi-filter" [label]="'common.actions.apply' | transloco" size="small" (onClick)="applyActivationFilters()" [loading]="isLoadingActivation()" />
                                <p-button icon="pi pi-times" [label]="'common.actions.clearAll' | transloco" size="small" severity="secondary" [outlined]="true" (onClick)="clearActivationFilters()" />
                                <p-button
                                    icon="pi pi-refresh"
                                    [ariaLabel]="'admin.system.console.refreshCard' | transloco"
                                    size="small"
                                    severity="secondary"
                                    [outlined]="true"
                                    (onClick)="loadSystemActivation(systemActivation()?.offset ?? 0)"
                                    [loading]="isLoadingActivation()"
                                />
                            </div>
                        </div>
                        @if (activationCopyStatus() === "success") {
                        <div class="admin-panel__messages">
                            <p-message severity="success" styleClass="w-full" [text]="'admin.system.activation.copySuccess' | transloco" />
                        </div>
                        } @else if (activationCopyStatus() === "error") {
                        <div class="admin-panel__messages">
                            <p-message severity="error" styleClass="w-full" [text]="'admin.system.activation.copyError' | transloco" />
                        </div>
                        }
                        <div class="grid border-b border-surface-100 bg-surface-50 dark:border-surface-800 dark:bg-surface-800 md:grid-cols-3">
                            <div class="flex min-w-0 items-center justify-between gap-3 border-b border-surface-100 px-4 py-3 dark:border-surface-800 md:border-b-0 md:border-r">
                                <span class="text-xs font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.activation.metrics.liveSites" | transloco }}</span>
                                <strong class="truncate font-bold text-[var(--p-text-color)]">{{ activationLiveSites() | number }}</strong>
                            </div>
                            <div class="flex min-w-0 items-center justify-between gap-3 border-b border-surface-100 px-4 py-3 dark:border-surface-800 md:border-b-0 md:border-r">
                                <span class="text-xs font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.activation.metrics.loadedRows" | transloco }}</span>
                                <strong class="truncate font-bold text-[var(--p-text-color)]">{{ activationRows().length | number }}</strong>
                            </div>
                            <div class="flex min-w-0 items-center justify-between gap-3 px-4 py-3">
                                <span class="text-xs font-semibold text-[var(--p-text-muted-color)]">{{ "admin.system.activation.metrics.totalRows" | transloco }}</span>
                                <strong class="truncate font-bold text-[var(--p-text-color)]">{{ systemActivation()?.total ?? 0 | number }}</strong>
                            </div>
                        </div>
                        <div class="admin-table-wrap">
                            <p-table [value]="activationRows()" [loading]="isLoadingActivation()" [rowHover]="true" styleClass="p-datatable-sm admin-data-table">
                                <ng-template pTemplate="header">
                                    <tr>
                                        <th>{{ "admin.system.activation.columns.team" | transloco }}</th>
                                        <th>{{ "common.columns.domain" | transloco }}</th>
                                        <th>{{ "common.columns.status" | transloco }}</th>
                                        <th>{{ "admin.system.activation.columns.lastHit" | transloco }}</th>
                                        <th>{{ "admin.system.activation.columns.lastEvent" | transloco }}</th>
                                        <th>{{ "admin.system.activation.columns.hits24h" | transloco }}</th>
                                        <th>{{ "admin.system.activation.columns.hits7d" | transloco }}</th>
                                        <th>{{ "admin.system.activation.columns.events7d" | transloco }}</th>
                                        <th>{{ "common.columns.actions" | transloco }}</th>
                                    </tr>
                                </ng-template>
                                <ng-template pTemplate="body" let-row>
                                    <tr>
                                        <td>
                                            <div class="max-w-52 truncate font-semibold text-[var(--p-text-color)]">{{ row.team_name }}</div>
                                            <div class="mt-0.5 max-w-52 truncate text-xs font-medium text-[var(--p-text-muted-color)]">{{ row.owner_email || ("common.unknown" | transloco) }}</div>
                                            <div class="mt-0.5 max-w-52 truncate text-xs font-medium text-[var(--p-text-muted-color)]">{{ row.active_sites | number }} / {{ row.sites_count | number }} {{ "common.columns.sites" | transloco }}</div>
                                        </td>
                                        <td>
                                            <div class="max-w-52 truncate font-semibold text-[var(--p-text-color)]">{{ row.site_domain }}</div>
                                            @if (row.plan_name || row.plan_code || row.cloud_region) {
                                            <div class="mt-0.5 max-w-52 truncate text-xs font-medium text-[var(--p-text-muted-color)]">{{ row.plan_name || row.plan_code || "-" }} · {{ row.cloud_region || "-" }}</div>
                                            }
                                        </td>
                                        <td><p-tag [value]="activationStatusLabel(row.status)" [severity]="activationStatusSeverity(row.status)" /></td>
                                        <td>
                                            @if (row.last_hit_at) {
                                            <app-relative-date-time [value]="row.last_hit_at" />
                                            } @else { - }
                                        </td>
                                        <td>
                                            @if (row.last_event_at) {
                                            <app-relative-date-time [value]="row.last_event_at" />
                                            @if (row.last_event_name) {
                                            <div class="mt-0.5 max-w-36 truncate text-xs font-medium text-[var(--p-text-muted-color)]">{{ row.last_event_name }}</div>
                                            } } @else { - }
                                        </td>
                                        <td>{{ row.hits_last_24h | number }}</td>
                                        <td>{{ row.hits_last_7d | number }}</td>
                                        <td>{{ row.events_last_7d | number }}</td>
                                        <td>
                                            <app-table-row-actions [items]="activationRowActions(row)" [loading]="openingActivationTeamId() === row.team_id" />
                                        </td>
                                    </tr>
                                </ng-template>
                                <ng-template pTemplate="emptymessage">
                                    <tr>
                                        <td colspan="9" class="admin-empty-cell">{{ "admin.system.activation.empty" | transloco }}</td>
                                    </tr>
                                </ng-template>
                            </p-table>
                        </div>
                        <div class="flex items-center justify-between gap-4 border-t border-surface-100 px-4 py-3 text-sm text-[var(--p-text-muted-color)] dark:border-surface-800">
                            <span>{{ "admin.system.activation.pagination" | transloco: { loaded: activationRows().length, total: systemActivation()?.total ?? 0 } }}</span>
                            <div class="flex gap-2">
                                <p-button
                                    icon="pi pi-chevron-left"
                                    [label]="'common.previous' | transloco"
                                    size="small"
                                    severity="secondary"
                                    [outlined]="true"
                                    [disabled]="(systemActivation()?.offset ?? 0) <= 0 || isLoadingActivation()"
                                    (onClick)="loadSystemActivation(previousActivationOffset())"
                                />
                                <p-button
                                    icon="pi pi-chevron-right"
                                    iconPos="right"
                                    [label]="'common.next' | transloco"
                                    size="small"
                                    severity="secondary"
                                    [outlined]="true"
                                    [disabled]="!(systemActivation()?.has_more) || isLoadingActivation()"
                                    (onClick)="loadSystemActivation((systemActivation()?.offset ?? 0) + (systemActivation()?.limit ?? 50))"
                                />
                            </div>
                        </div>
                    </section>
                    }
                </p-tabpanel>

                <p-tabpanel value="audit">
                    @if (activeAdminTab() === "audit") {
                    <section class="admin-panel admin-panel--wide" aria-labelledby="audit-title">
                        <div class="admin-panel__header">
                            <div>
                                <h2 id="audit-title">{{ "admin.system.audit.title" | transloco }}</h2>
                            </div>
                        </div>
                        <app-system-audit />
                    </section>
                    }
                </p-tabpanel>
            </p-tabpanels>
        </p-tabs>
        }
    </div>
</app-admin-page-frame>
