<section class="admin-analytics-page">
  <div class="toolbar">
    <div class="ranges">
      @for (range of ranges; track range) {
        <app-button [variant]="facade.dateRange() === range ? 'primary' : 'secondary'" size="sm" (click)="facade.setDateRange(range)">{{ range }}d</app-button>
      }
    </div>
    <div class="toolbar-actions">
      <app-button variant="secondary" size="sm" (click)="print()">{{ 'adminAnalytics.print' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="exportCsv()">{{ 'adminOrders.export' | translate }}</app-button>
    </div>
  </div>

  @if (facade.error()) {
    <app-empty-state [title]="'common.errorTitle' | translate" [description]="'common.errorDescription' | translate">
      <span slot="actions">
        <app-button variant="primary" (click)="facade.load()">{{ 'common.retry' | translate }}</app-button>
      </span>
    </app-empty-state>
  } @else {

  <div class="tabs" role="tablist" [attr.aria-label]="'adminAnalytics.tabsLabel' | translate">
    @for (tab of tabs; track tab) {
      <button
        type="button"
        role="tab"
        class="tab"
        [class.tab--active]="activeTab() === tab"
        [attr.aria-selected]="activeTab() === tab"
        [attr.id]="'tab-' + tab"
        [attr.aria-controls]="'panel-' + tab"
        (click)="selectTab(tab)"
      >{{ 'adminAnalytics.tab.' + tab | translate }}</button>
    }
  </div>

  @if (activeTab() === 'overview') {
    <div class="panel" role="tabpanel" id="panel-overview" aria-labelledby="tab-overview">
      @if (facade.loading()) {
        <div class="summary-grid" role="status" aria-live="polite" aria-busy="true">
          @for (i of [1,2,3,4,5,6]; track i) {
            <app-skeleton shape="rect" height="64px" />
          }
          <span class="sr-only">{{ 'common.loading' | translate }}</span>
        </div>
      } @else if (facade.summary(); as summary) {
        <div class="summary-grid">
          <div class="summary-card"><span>{{ 'adminAnalytics.revenue' | translate }}</span><strong>{{ summary.revenueTotal }} {{ summary.currency }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.orders' | translate }}</span><strong>{{ summary.ordersCount }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.customers' | translate }}</span><strong>{{ summary.customersCount }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.avgOrderValue' | translate }}</span><strong>{{ summary.avgOrderValue }} {{ summary.currency }}</strong></div>
          <div class="summary-card pending"><span>{{ 'adminAnalytics.conversion' | translate }}</span><app-badge variant="neutral">{{ 'adminAnalytics.unknown' | translate }}</app-badge></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.completionPercent' | translate }}</span><strong>{{ facade.healthCompletionPercent() }}%</strong></div>
        </div>
      }

      <div class="card">
        <h2>{{ 'adminAnalytics.salesChart' | translate }}</h2>
        <div class="chart">
          @for (point of facade.salesSeries(); track point.date) {
            <div class="bar" [style.height.%]="barHeight(point.value)" [title]="point.date + ': ' + point.value"></div>
          }
        </div>
      </div>

      <div class="grid-2">
        <div class="card">
          <h2>{{ 'adminAnalytics.topProducts' | translate }}</h2>
          @if (facade.loading()) {
            <div class="skeleton-rows" role="status" aria-live="polite" aria-busy="true">
              @for (i of [1,2,3]; track i) { <app-skeleton shape="rect" height="36px" /> }
              <span class="sr-only">{{ 'common.loading' | translate }}</span>
            </div>
          } @else if (facade.topProducts().length === 0) {
            <app-empty-state [title]="'adminAnalytics.topProductsEmptyTitle' | translate" [description]="'adminAnalytics.topProductsEmptyDescription' | translate" />
          } @else {
            <app-table>
              <thead><tr><th scope="col">{{ 'adminProducts.name' | translate }}</th><th scope="col">{{ 'adminAnalytics.quantitySold' | translate }}</th><th scope="col">{{ 'adminAnalytics.revenue' | translate }}</th></tr></thead>
              <tbody>
                @for (product of facade.topProducts(); track product.productId) {
                  <tr><th scope="row">{{ product.name }}</th><td>{{ product.quantity }}</td><td>{{ product.revenue }}</td></tr>
                }
              </tbody>
            </app-table>
          }
        </div>

        <div class="card">
          <h2>{{ 'adminAnalytics.lowStock' | translate }}</h2>
          @if (facade.lowStockProducts().length === 0) {
            <app-empty-state [title]="'adminAnalytics.lowStockEmptyTitle' | translate" />
          } @else {
            <app-table>
              <thead><tr><th scope="col">{{ 'adminProducts.name' | translate }}</th><th scope="col">{{ 'adminAnalytics.quantity' | translate }}</th><th scope="col">{{ 'adminAnalytics.status' | translate }}</th></tr></thead>
              <tbody>
                @for (product of facade.lowStockProducts(); track product.productId) {
                  <tr>
                    <th scope="row">{{ product.name }}</th>
                    <td>{{ product.quantity }}</td>
                    <td><app-badge [variant]="product.stockStatus === 'out_of_stock' ? 'danger' : 'warning'">{{ ('adminProducts.' + (product.stockStatus === 'out_of_stock' ? 'outOfStock' : 'lowStock')) | translate }}</app-badge></td>
                  </tr>
                }
              </tbody>
            </app-table>
          }
        </div>
      </div>

      <div class="grid-2">
        <div class="card">
          <h2>{{ 'adminAnalytics.recentActivity' | translate }}</h2>
          @if (facade.recentActivity().length === 0) {
            <app-empty-state [title]="'adminAnalytics.recentActivityEmptyTitle' | translate" />
          } @else {
            <ul class="activity-list">
              @for (entry of facade.recentActivity(); track entry.id) {
                <li>{{ entry.labelKey | translate }} <span class="muted">{{ entry.timestamp | date:'short' }}</span></li>
              }
            </ul>
          }
        </div>

        <div class="card">
          <h2>{{ 'adminAnalytics.warnings' | translate }}</h2>
          @if (facade.warnings().length === 0) {
            <app-empty-state [title]="'adminMarketplaceHealth.recommendNone' | translate" />
          } @else {
            <ul class="warning-list">
              @for (card of facade.warnings(); track card.id) {
                <li><app-badge [variant]="severityVariant(card.severity)">{{ card.labelKey | translate }}</app-badge></li>
              }
            </ul>
          }
        </div>
      </div>
    </div>
  }

  @if (activeTab() === 'health') {
    <div class="panel" role="tabpanel" id="panel-health" aria-labelledby="tab-health">
      <div class="card">
        <div class="card-head">
          <h2>{{ 'adminMarketplaceHealth.title' | translate }}</h2>
          <app-button variant="secondary" size="sm" (click)="exportHealthCsv()">{{ 'adminOrders.export' | translate }}</app-button>
        </div>
        <div class="health-widget__bar" role="progressbar" [attr.aria-valuenow]="facade.healthCompletionPercent()" aria-valuemin="0" aria-valuemax="100">
          <div class="health-widget__bar-fill" [style.width.%]="facade.healthCompletionPercent()"></div>
        </div>
        <p class="health-percent">{{ facade.healthCompletionPercent() }}% {{ 'adminMarketplaceHealth.complete' | translate }}</p>
        <ul class="health-checks">
          @for (check of facade.marketplaceHealth(); track check.code) {
            <li>
              <app-badge [variant]="healthStatusVariant(check.status)">{{ check.status === 'unknown' ? ('adminAnalytics.unknown' | translate) : (check.displayValue ?? check.status) }}</app-badge>
              <a [routerLink]="check.actionRoute">{{ check.labelKey | translate }}</a>
            </li>
          }
        </ul>
      </div>
    </div>
  }

  @if (activeTab() === 'products') {
    <div class="panel" role="tabpanel" id="panel-products" aria-labelledby="tab-products">
      @if (facade.productAnalytics(); as pa) {
        <div class="summary-grid">
          <div class="summary-card pending"><span>{{ 'adminAnalytics.topViewed' | translate }}</span><app-badge variant="neutral">{{ 'adminAnalytics.unknown' | translate }}</app-badge></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.hiddenProducts' | translate }}</span><strong>{{ pa.hiddenCount }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.archivedProducts' | translate }}</span><strong>{{ pa.archivedCount }}</strong></div>
        </div>
        <div class="grid-2">
          <div class="card">
            <h2>{{ 'adminAnalytics.mostReviewed' | translate }}</h2>
            @if (pa.mostReviewed.length === 0) {
              <app-empty-state [title]="'adminAnalytics.noReviewedProducts' | translate" />
            } @else {
              <app-table>
                <thead><tr><th scope="col">{{ 'adminProducts.name' | translate }}</th><th scope="col">{{ 'adminAnalytics.reviewCount' | translate }}</th></tr></thead>
                <tbody>@for (row of pa.mostReviewed; track row.productId) { <tr><td>{{ row.name }}</td><td>{{ row.value }}</td></tr> }</tbody>
              </app-table>
            }
          </div>
          <div class="card">
            <h2>{{ 'adminAnalytics.worstRated' | translate }}</h2>
            @if (pa.worstRated.length === 0) {
              <app-empty-state [title]="'adminAnalytics.noReviewedProducts' | translate" />
            } @else {
              <app-table>
                <thead><tr><th scope="col">{{ 'adminProducts.name' | translate }}</th><th scope="col">{{ 'adminAnalytics.avgRating' | translate }}</th></tr></thead>
                <tbody>@for (row of pa.worstRated; track row.productId) { <tr><td>{{ row.name }}</td><td>{{ row.value }}</td></tr> }</tbody>
              </app-table>
            }
          </div>
        </div>
      }
    </div>
  }

  @if (activeTab() === 'customers') {
    <div class="panel" role="tabpanel" id="panel-customers" aria-labelledby="tab-customers">
      @if (facade.customerAnalytics(); as ca) {
        <div class="summary-grid">
          <div class="summary-card"><span>{{ 'adminAnalytics.newCustomers' | translate }}</span><strong>{{ ca.newCustomers }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.returningCustomers' | translate }}</span><strong>{{ ca.returningCustomers }}</strong></div>
          <div class="summary-card"><span>{{ 'adminAnalytics.averageSpend' | translate }}</span><strong>{{ ca.averageSpend }} {{ ca.currency }}</strong></div>
          <div class="summary-card">
            <span>{{ 'adminAnalytics.retention' | translate }}</span>
            @if (ca.retentionPercent === null) {
              <app-badge variant="neutral">{{ 'adminAnalytics.unknown' | translate }}</app-badge>
            } @else {
              <strong>{{ ca.retentionPercent }}%</strong>
            }
          </div>
        </div>
      }
    </div>
  }

  @if (activeTab() === 'search') {
    <div class="panel" role="tabpanel" id="panel-search" aria-labelledby="tab-search">
      <div class="card pending-section">
        <h2>{{ 'adminAnalytics.searchAnalytics' | translate }}</h2>
        <p><app-badge variant="neutral">{{ 'adminAnalytics.unknown' | translate }}</app-badge> {{ 'adminAnalytics.pendingBackendHint' | translate }}</p>
      </div>
    </div>
  }

  @if (activeTab() === 'traffic') {
    <div class="panel" role="tabpanel" id="panel-traffic" aria-labelledby="tab-traffic">
      <div class="card pending-section">
        <h2>{{ 'adminAnalytics.trafficAnalytics' | translate }}</h2>
        <p><app-badge variant="neutral">{{ 'adminAnalytics.unknown' | translate }}</app-badge> {{ 'adminAnalytics.availableAfterBackend' | translate }}</p>
      </div>
    </div>
  }

  @if (activeTab() === 'recommendations') {
    <div class="panel" role="tabpanel" id="panel-recommendations" aria-labelledby="tab-recommendations">
      <div class="card">
        <h2>{{ 'adminMarketplaceHealth.recommendationsTitle' | translate }}</h2>
        @if (facade.recommendations().length === 0) {
          <app-empty-state [title]="'adminMarketplaceHealth.recommendNone' | translate" />
        } @else {
          <ul class="recommendation-list">
            @for (card of facade.recommendations(); track card.id) {
              <li>
                <app-badge [variant]="severityVariant(card.severity)">{{ 'adminMarketplaceHealth.severity.' + card.severity | translate }}</app-badge>
                <a [routerLink]="card.route">{{ card.labelKey | translate }}</a>
                @if (card.descriptionKey) { <span class="muted">{{ card.descriptionKey | translate }}</span> }
              </li>
            }
          </ul>
        }
      </div>
    </div>
  }
  }
</section>
