<div class="flex flex-col h-full w-full bg-[var(--p-surface-ground)] transition-colors duration-200">
    <!-- Header & Controls -->
    <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]="statsService.isLoading()"
        (selectedRangeChange)="selectedRange.set($event)"
        (customRangeDatesChange)="customRangeDates.set($event)"
        (refresh)="refreshAll()"
    >
    </app-range-toolbar>
    @if (showOnboarding()) {
    <section class="mb-6 rounded-md border border-surface-200 bg-surface-0 p-4 shadow-sm dark:border-surface-700 dark:bg-surface-900" aria-labelledby="dashboard-onboarding-title">
        <div class="flex items-start justify-between gap-3">
            <div class="min-w-0 flex-1">
                <div class="flex flex-wrap items-center gap-2">
                    <h2 id="dashboard-onboarding-title" class="m-0 text-base font-semibold text-[var(--p-text-color)]">{{ "dashboard.onboarding.title" | transloco }}</h2>
                    <span class="rounded border border-surface-200 px-2 py-0.5 text-xs font-semibold text-[var(--p-text-muted-color)] dark:border-surface-700"> {{ "dashboard.onboarding.progress" | transloco: onboardingProgress() }} </span>
                </div>
            </div>
            <p-button
                icon="pi pi-times"
                [text]="true"
                [rounded]="true"
                size="small"
                [ariaLabel]="'dashboard.onboarding.dismiss' | transloco"
                [pTooltip]="'dashboard.onboarding.dismiss' | transloco"
                tooltipPosition="top"
                styleClass="shrink-0"
                (onClick)="dismissOnboarding()"
            />
        </div>
        <app-workflow-progress class="mt-4 block" [steps]="onboardingRailSteps()" [ariaLabel]="'dashboard.onboarding.title' | transloco" />
        @if (currentOnboardingStep(); as step) {
        <div class="mt-4 flex flex-col gap-3 rounded border border-surface-200 bg-surface-50 p-3 dark:border-surface-700 dark:bg-surface-800 sm:flex-row sm:items-center sm:justify-between">
            <div class="min-w-0">
                <span class="block text-xs font-semibold uppercase tracking-wide text-[var(--p-text-muted-color)]">{{ "dashboard.onboarding.current" | transloco }}</span>
                <strong class="block text-sm text-[var(--p-text-color)]">{{ onboardingStepLabel(step) }}</strong>
            </div>
            <p-button [label]="onboardingStepAction(step)" size="small" severity="secondary" [outlined]="true" styleClass="justify-center" (onClick)="runOnboardingAction(step)" />
        </div>
        }
    </section>
    } @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()) {
    <!-- KPI Cards -->
    <!-- TODO: Refactor for mobile, weird UX -->
    <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 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" [delta]="card.delta ?? null" [invertDelta]="card.invertDelta ?? false" />
        }
    </div>

    <!-- Traffic Chart -->
    <div class="mb-6">
        <p-card class="shadow-sm border border-surface-200 dark:border-surface-700 surface-card">
            <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-2">
                    <h3 class="text-lg font-semibold">{{ chartTitle() }}</h3>
                    @if (hasFilters()) {
                    <span class="inline-flex items-center px-2 py-0.5 rounded-full border border-[var(--p-primary-color)] text-xs font-medium"> {{ "dashboard.filteredBadge" | transloco }} </span>
                    }
                </div>
            </div>
            <app-traffic-chart
                [data]="statsService.stats()?.chart_data || []"
                [comparisonData]="statsService.stats()?.comparison?.chart_data || []"
                [isLoading]="statsService.isLoading()"
                [isShortRange]="isShortRange()"
                [comparisonLabel]="comparisonLabel()"
                (snippetClicked)="openTrackingSettings()"
            />
        </p-card>
    </div>

    <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
        @let chips = filterChips();
        <div class="flex flex-wrap items-center gap-2">
            @if (chips.length) { @for (filter of chips; track filter.type) {
            <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)]">{{ filter.label }}</span>
                <button type="button" class="text-muted-color hover:text-[var(--p-text-color)]" (click)="removeFilter(filter.type, filter.value)" [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)="clearFilter()">{{ "common.actions.clearAll" | transloco }}</button>
            } @else {
            <span class="text-sm text-[var(--p-text-muted-color)]">{{ "common.noActiveFilter" | transloco }}</span>
            }
        </div>
        <div class="flex items-center gap-2">
            <p-splitButton
                icon="pi pi-download"
                [label]="isExportingFiltered() ? ('common.preparing' | transloco) : ('common.actions.exportCsv' | transloco)"
                [model]="exportMenuItems()"
                [disabled]="!exportUrl() || isExportingFiltered()"
                styleClass="p-button-outlined p-button-sm"
                (onClick)="exportFiltered('csv')"
            />
        </div>
    </div>
    @if (filteredExportState() === "success") {
    <div class="mb-6 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">{{ "dashboard.exportStatus.success" | transloco }}</div>
    } @if (filteredExportState() === "error") {
    <div class="mb-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{{ "dashboard.exportStatus.error" | transloco }}</div>
    }

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

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
        <app-goal-list [data]="statsService.stats()?.goals || []" [siteId]="siteService.activeSite()?.id || null" [readOnly]="isShareMode()" [isLoading]="statsService.isLoading()" (refresh)="refreshAll()" />

        <app-funnel-list [funnels]="statsService.stats()?.funnels || []" [isLoading]="statsService.isLoading()" [readOnly]="isShareMode()" (manageClicked)="openFunnelManager()" (funnelClicked)="openFunnelViewer($event)" />
    </div>

    @if (!isShareMode()) {
    <app-funnel-manager
        [visible]="showFunnelManager()"
        (visibleChange)="setFunnelManagerVisible($event)"
        [siteId]="siteService.activeSite()?.id || null"
        [editFunnelId]="funnelEditRequestId()"
        (funnelsChanged)="refreshAll()"
        (viewFunnel)="openFunnelViewer($event)"
    />
    }

    <app-funnel-viewer
        [visible]="showFunnelViewer()"
        (visibleChange)="showFunnelViewer.set($event)"
        [siteId]="siteService.activeSite()?.id || null"
        [funnelId]="selectedFunnelId()"
        [dateRange]="funnelDateRange()"
        [canEdit]="!isShareMode()"
        (editClicked)="editSelectedFunnel()"
    />

    <!-- Hits Table -->
    <p-card class="shadow-sm border border-surface-200 dark:border-surface-700 surface-card">
        <div class="flex flex-col sm:flex-row sm:items-center justify-between mb-4 gap-4">
            <h3 class="text-lg font-semibold">{{ "dashboard.rawHitsTitle" | transloco }}</h3>
            <p-iconfield>
                <p-inputicon class="pi pi-search" />
                <input pInputText (input)="onSearch($event)" [placeholder]="'common.searchPlaceholder' | transloco" class="w-full sm:w-64" />
            </p-iconfield>
        </div>

        <p-table
            [value]="hitService.hits()"
            [lazy]="true"
            (onLazyLoad)="loadHits($event)"
            [totalRecords]="hitService.total()"
            [loading]="hitService.isLoading()"
            [rows]="10"
            [paginator]="true"
            [rowsPerPageOptions]="[10, 25, 50]"
            [rowHover]="true"
            responsiveLayout="scroll"
            class="p-datatable-sm"
            sortField="timestamp"
            [sortOrder]="-1"
            [tableStyle]="{ 'min-width': '760px' }"
        >
            <ng-template pTemplate="header">
                <tr>
                    <th pSortableColumn="path">
                        {{ "common.columns.path" | transloco }}
                        <p-sortIcon field="path" />
                    </th>
                    <th pSortableColumn="timestamp">
                        {{ "common.columns.time" | transloco }}
                        <p-sortIcon field="timestamp" />
                    </th>
                    <th pSortableColumn="referrer">
                        {{ "common.columns.referrer" | transloco }}
                        <p-sortIcon field="referrer" />
                    </th>
                    <th>{{ "common.columns.device" | transloco }}</th>
                </tr>
            </ng-template>

            <ng-template pTemplate="body" let-hit>
                <tr class="text-sm hover:bg-[var(--p-surface-hover)]">
                    <td class="font-medium truncate max-w-[200px]" [title]="hit.path">
                        <div class="flex items-center gap-2 min-w-0">
                            @if (siteFaviconUrl(); as favicon) {
                            <img [ngSrc]="favicon" class="size-4 shrink-0 rounded-full" [width]="16" [height]="16" alt="" />
                            } @if (buildSiteUrl(hit.path); as pageUrl) {
                            <span class="truncate" [title]="hit.path">{{ hit.path }}</span>
                            <a class="shrink-0 text-muted-color hover:text-[var(--p-text-color)]" [href]="pageUrl" target="_blank" rel="noopener noreferrer" [attr.aria-label]="'dashboard.openPageInNewTabAria' | transloco">
                                <i class="pi pi-external-link text-xs" aria-hidden="true"></i>
                            </a>
                            } @else {
                            <span class="truncate" [title]="hit.path">{{ hit.path }}</span>
                            }
                        </div>
                    </td>
                    <td class="whitespace-nowrap text-muted-color"><app-relative-date-time [value]="hit.timestamp" /></td>
                    <td class="truncate max-w-[200px] text-muted-color" [title]="hit.referrer">
                        @if (hit.referrer) {
                        <div class="flex items-center gap-2 min-w-0">
                            @if (referrerDomain(hit.referrer); as domain) { @if (faviconUrlForDomain(domain); as favicon) {
                            <img [ngSrc]="favicon" class="size-4 shrink-0 rounded-full" [width]="16" [height]="16" alt="" />
                            } } @if (buildReferrerUrl(hit.referrer); as referrerUrl) {
                            <span class="truncate" [title]="hit.referrer">{{ displayReferrerUrl(hit.referrer) }}</span>
                            <a class="shrink-0 text-muted-color hover:text-[var(--p-text-color)]" [href]="referrerUrl" target="_blank" rel="noopener noreferrer" [attr.aria-label]="'dashboard.openReferrerInNewTabAria' | transloco">
                                <i class="pi pi-external-link text-xs" aria-hidden="true"></i>
                            </a>
                            } @else {
                            <span class="truncate">{{ hit.referrer }}</span>
                            }
                        </div>
                        } @else {
                        <span>{{ "common.direct" | transloco }}</span>
                        }
                    </td>
                    <td>
                        <div class="inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs border border-surface-200 dark:border-surface-700 bg-surface-100 dark:bg-surface-800">
                            <i [class]="(hit.viewport_width ?? 0) > 768 ? 'pi pi-desktop' : 'pi pi-mobile'" aria-hidden="true"></i>
                            {{ (hit.viewport_width ?? 0) > 768 ? ("common.devices.desktop" | transloco) : ("common.devices.mobile" | transloco) }}
                        </div>
                    </td>
                </tr>
            </ng-template>
        </p-table>
    </p-card>
    @if (searchConsoleDateRange(); as searchConsoleRange) {
    <app-search-console-drilldown
        class="mt-6 block"
        [siteId]="siteService.activeSite()?.id || null"
        [siteDomain]="siteService.activeSite()?.domain || null"
        [from]="searchConsoleRange.from"
        [to]="searchConsoleRange.to"
        [path]="searchConsoleFilters().path"
        [country]="searchConsoleFilters().country"
        [device]="searchConsoleFilters().device"
        [shareMode]="isShareMode()"
        [refreshKey]="searchConsoleRefreshKey()"
    />
    } } @else {
    <div class="flex flex-col items-center justify-center h-[50vh] gap-4">
        <i class="pi pi-globe text-6xl text-primary opacity-20"></i>
        @if (emptyTeamName(); as teamName) {
        <h2 class="text-2xl font-semibold text-muted-color">{{ "dashboard.empty.teamTitle" | transloco: { team: teamName } }}</h2>
        <p class="text-center text-muted-color max-w-xl">{{ "dashboard.empty.teamDescription" | transloco: { team: teamName } }}</p>
        } @else {
        <h2 class="text-2xl font-semibold text-muted-color">{{ "common.noSiteSelected" | transloco }}</h2>
        <p class="text-muted-color">{{ "dashboard.noSiteDescription" | transloco }}</p>
        } @if (!isShareMode()) {
        <p-button [label]="'dashboard.empty.createSite' | transloco" icon="pi pi-plus" size="small" (onClick)="isAddSiteVisible.set(true)" />
        }
    </div>
    } @if (!isShareMode()) { @defer (when isAddSiteVisible()) {
    <app-add-site-dialog [visible]="isAddSiteVisible()" (visibleChange)="isAddSiteVisible.set($event)" />
    } }
</div>
<!-- Date Range Dialog -->
