<div class="flex flex-col h-full w-full bg-[var(--p-surface-ground)] transition-colors duration-200">
    <app-page-header>
        <ng-template appPageHeaderLeft>
            <div>
                <app-page-breadcrumb [items]="breadcrumbItems()" />
            </div>
        </ng-template>
    </app-page-header>

    <app-range-toolbar
        [timeRanges]="timeRanges()"
        [selectedRange]="selectedRange()"
        [customRangeDates]="customRangeDates()"
        [loading]="isLoading()"
        (selectedRangeChange)="selectedRange.set($event)"
        (customRangeDatesChange)="customRangeDates.set($event)"
        (refresh)="refreshData()"
    >
        <a
            toolbar-right
            pButton
            [href]="ecommerceDocsUrl"
            target="_blank"
            rel="noreferrer"
            size="small"
            icon="pi pi-external-link"
            iconPos="right"
            [label]="'ecommerce.docsAction' | transloco"
            [attr.aria-label]="'ecommerce.docsAction' | transloco"
            class="p-button-rounded p-button-secondary"
        ></a>
    </app-range-toolbar>

    @if (siteService.isLoading()) {
    <div class="flex items-center gap-2 text-sm text-[var(--p-text-muted-color)]">
        <i class="pi pi-spin pi-spinner" aria-hidden="true"></i>
        <span>{{ "common.loadingSiteData" | transloco }}</span>
    </div>
    } @else if (siteService.activeSite()) {
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        @for (card of kpiCards(); track card.label) {
        <app-kpi-card [label]="card.label" [value]="card.value" [loading]="card.loading" [valueClass]="card.valueClass" />
        }
    </div>

    <div class="mb-6">
        <p-card class="shadow-sm border border-surface-200 dark:border-surface-700 surface-card">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
                <div>
                    <h3 class="text-lg font-semibold">{{ "ecommerce.chart.title" | transloco }}</h3>
                    <p class="text-sm text-[var(--p-text-muted-color)]">{{ "ecommerce.chart.description" | transloco }}</p>
                </div>
            </div>

            <app-series-chart [data]="chartData()" [series]="chartConfig()" [isLoading]="isLoading()" [isShortRange]="isShortRange()" [emptyTitle]="'ecommerce.empty.title' | transloco" [emptyDescription]="'ecommerce.empty.description' | transloco" />
        </p-card>
    </div>

    <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div class="flex flex-wrap items-center gap-2">
            @if (hasFilters()) { @for (chip of filterChips(); track chip.key) {
            <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full border border-[var(--p-primary-color)] text-sm">
                <span class="font-medium text-[var(--p-text-color)]">{{ chip.label }}</span>
                <button type="button" class="text-muted-color hover:text-[var(--p-text-color)]" (click)="chip.remove()" [attr.aria-label]="'common.removeFilterAria' | transloco">
                    <i class="pi pi-times" aria-hidden="true"></i>
                </button>
            </span>
            }
            <button type="button" class="text-xs text-muted-color hover:text-[var(--p-text-color)] underline" (click)="clearAllFilters()">{{ "common.actions.clearAll" | transloco }}</button>
            } @else {
            <span class="text-sm text-[var(--p-text-muted-color)]">{{ "common.noActiveFilter" | transloco }}</span>
            }
        </div>
    </div>

    <app-metric-card-group class="mb-6" [tabs]="metricCardTabs()" (rowClicked)="onMetricCardClick($event)" />

    <div>
        <p-card class="shadow-sm border border-surface-200 dark:border-surface-700 surface-card">
            <div class="flex items-start justify-between gap-3 mb-4">
                <div>
                    <h3 class="text-lg font-semibold">{{ "ecommerce.breakdowns.title" | transloco }}</h3>
                </div>
            </div>

            <p-tabs value="products" [scrollable]="true">
                <p-tablist>
                    <p-tab value="products">{{ "ecommerce.products.title" | transloco }}</p-tab>
                    <p-tab value="sources">{{ "ecommerce.sources.title" | transloco }}</p-tab>
                </p-tablist>

                <p-tabpanels>
                    <p-tabpanel value="products">
                        <div class="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                            <p class="text-sm text-[var(--p-text-muted-color)]">{{ "ecommerce.products.description" | transloco }}</p>
                            <p-iconfield class="w-full sm:w-64">
                                <p-inputicon class="pi pi-search" />
                                <input pInputText #productSearch [placeholder]="'common.searchPlaceholder' | transloco" (input)="productsTable.filterGlobal($any($event.target).value, 'contains')" class="w-full" />
                            </p-iconfield>
                        </div>
                        <p-table
                            #productsTable
                            [value]="products()"
                            [loading]="isLoading()"
                            [globalFilterFields]="['item_name', 'item_id', 'quantity', 'orders', 'revenue']"
                            [paginator]="true"
                            [rows]="10"
                            [rowsPerPageOptions]="[10, 25, 50]"
                            [rowHover]="true"
                            responsiveLayout="scroll"
                            sortField="revenue"
                            [sortOrder]="-1"
                            styleClass="p-datatable-sm"
                            [tableStyle]="{ 'min-width': '720px' }"
                        >
                            <ng-template pTemplate="header">
                                <tr>
                                    <th pSortableColumn="item_name">
                                        {{ "ecommerce.columns.product" | transloco }}
                                        <p-sortIcon field="item_name" />
                                    </th>
                                    <th pSortableColumn="quantity" class="text-right">
                                        {{ "ecommerce.columns.quantity" | transloco }}
                                        <p-sortIcon field="quantity" />
                                    </th>
                                    <th pSortableColumn="orders" class="text-right">
                                        {{ "ecommerce.columns.orders" | transloco }}
                                        <p-sortIcon field="orders" />
                                    </th>
                                    <th pSortableColumn="revenue" class="text-right">
                                        {{ "ecommerce.columns.revenue" | transloco }}
                                        <p-sortIcon field="revenue" />
                                    </th>
                                </tr>
                            </ng-template>
                            <ng-template pTemplate="body" let-product>
                                <tr
                                    class="ecommerce-filter-row"
                                    [class.ecommerce-filter-row--active]="isProductFilterActive(product)"
                                    role="button"
                                    tabindex="0"
                                    (click)="toggleProductFilter(product)"
                                    (keydown.enter)="toggleProductFilter(product)"
                                    (keydown.space)="$event.preventDefault(); toggleProductFilter(product)"
                                >
                                    <td>
                                        <div class="flex flex-col">
                                            <span class="font-medium">{{ product.item_name || product.item_id }}</span>
                                            @if (product.item_id) {
                                            <span class="text-xs text-[var(--p-text-muted-color)]">{{ product.item_id }}</span>
                                            }
                                        </div>
                                    </td>
                                    <td class="text-right">{{ formatNumber(product.quantity) }}</td>
                                    <td class="text-right">{{ formatNumber(product.orders) }}</td>
                                    <td class="text-right">{{ formatMoney(product.revenue, resolveCurrency(summary()?.currency)) }}</td>
                                </tr>
                            </ng-template>
                            <ng-template pTemplate="emptymessage">
                                <tr>
                                    <td colspan="4" class="text-center text-sm text-[var(--p-text-muted-color)] py-8">{{ "ecommerce.products.empty" | transloco }}</td>
                                </tr>
                            </ng-template>
                        </p-table>
                    </p-tabpanel>

                    <p-tabpanel value="sources">
                        <div class="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                            <p class="text-sm text-[var(--p-text-muted-color)]">{{ "ecommerce.sources.description" | transloco }}</p>
                            <p-iconfield class="w-full sm:w-64">
                                <p-inputicon class="pi pi-search" />
                                <input pInputText #sourceSearch [placeholder]="'common.searchPlaceholder' | transloco" (input)="sourcesTable.filterGlobal($any($event.target).value, 'contains')" class="w-full" />
                            </p-iconfield>
                        </div>
                        <p-table
                            #sourcesTable
                            [value]="sources()"
                            [loading]="isLoading()"
                            [globalFilterFields]="['utm_source', 'utm_medium', 'utm_campaign', 'referrer', 'orders', 'revenue']"
                            [paginator]="true"
                            [rows]="10"
                            [rowsPerPageOptions]="[10, 25, 50]"
                            [rowHover]="true"
                            responsiveLayout="scroll"
                            sortField="revenue"
                            [sortOrder]="-1"
                            styleClass="p-datatable-sm"
                            [tableStyle]="{ 'min-width': '760px' }"
                        >
                            <ng-template pTemplate="header">
                                <tr>
                                    <th pSortableColumn="utm_source">
                                        {{ "ecommerce.columns.source" | transloco }}
                                        <p-sortIcon field="utm_source" />
                                    </th>
                                    <th pSortableColumn="utm_campaign">
                                        {{ "ecommerce.columns.campaign" | transloco }}
                                        <p-sortIcon field="utm_campaign" />
                                    </th>
                                    <th pSortableColumn="referrer">
                                        {{ "ecommerce.columns.referrer" | transloco }}
                                        <p-sortIcon field="referrer" />
                                    </th>
                                    <th pSortableColumn="orders" class="text-right">
                                        {{ "ecommerce.columns.orders" | transloco }}
                                        <p-sortIcon field="orders" />
                                    </th>
                                    <th pSortableColumn="revenue" class="text-right">
                                        {{ "ecommerce.columns.revenue" | transloco }}
                                        <p-sortIcon field="revenue" />
                                    </th>
                                </tr>
                            </ng-template>
                            <ng-template pTemplate="body" let-source>
                                <tr
                                    class="ecommerce-filter-row"
                                    [class.ecommerce-filter-row--active]="isSourceFilterActive(source)"
                                    role="button"
                                    tabindex="0"
                                    (click)="toggleSourceFilter(source)"
                                    (keydown.enter)="toggleSourceFilter(source)"
                                    (keydown.space)="$event.preventDefault(); toggleSourceFilter(source)"
                                >
                                    <td>
                                        <div class="flex flex-col">
                                            <span class="font-medium" [title]="source.utm_source">{{ source.utm_source }}</span>
                                            <span class="text-xs text-[var(--p-text-muted-color)]">{{ source.utm_medium }}</span>
                                        </div>
                                    </td>
                                    <td>{{ source.utm_campaign }}</td>
                                    <td>
                                        @if (source.referrer) {
                                        <div class="ecommerce-source-cell text-[var(--p-text-muted-color)]">
                                            @if (sourceDomain(source.referrer); as domain) { @if (faviconUrlForDomain(domain); as favicon) {
                                            <img [ngSrc]="favicon" class="ecommerce-source-cell__favicon" [width]="16" [height]="16" alt="" />
                                            } } @if (sourceLinkUrl(source.referrer); as referrerUrl) {
                                            <span class="ecommerce-source-cell__label" [title]="source.referrer">{{ sourceDisplayUrl(source.referrer) }}</span>
                                            <a class="ecommerce-source-cell__link" [href]="referrerUrl" target="_blank" rel="noopener noreferrer" (click)="$event.stopPropagation()" [attr.aria-label]="'common.openInNewTabAria' | transloco">
                                                <i class="pi pi-external-link ecommerce-source-cell__link-icon" aria-hidden="true"></i>
                                            </a>
                                            } @else {
                                            <span class="ecommerce-source-cell__label" [title]="source.referrer">{{ source.referrer }}</span>
                                            }
                                        </div>
                                        } @else {
                                        <span class="text-[var(--p-text-muted-color)]">{{ "common.direct" | transloco }}</span>
                                        }
                                    </td>
                                    <td class="text-right">{{ formatNumber(source.orders) }}</td>
                                    <td class="text-right">{{ formatMoney(source.revenue, resolveCurrency(summary()?.currency)) }}</td>
                                </tr>
                            </ng-template>
                            <ng-template pTemplate="emptymessage">
                                <tr>
                                    <td colspan="5" class="text-center text-sm text-[var(--p-text-muted-color)] py-8">{{ "ecommerce.sources.empty" | transloco }}</td>
                                </tr>
                            </ng-template>
                        </p-table>
                    </p-tabpanel>
                </p-tabpanels>
            </p-tabs>
        </p-card>
    </div>
    } @else {
    <div class="flex flex-col items-center justify-center h-[50vh] gap-4">
        <i class="pi pi-shopping-bag text-6xl text-primary opacity-20"></i>
        <h2 class="text-2xl font-semibold text-muted-color">{{ "common.noSiteSelected" | transloco }}</h2>
        <p class="text-muted-color">{{ "ecommerce.noSiteDescription" | transloco }}</p>
    </div>
    }
</div>
