<main class="catalog-page page-container">
  <header class="catalog-header">
    <button type="button" class="catalog-root-link catalog-root-link-btn" (click)="browseCategories()">{{ 'catalog.title' | translate }}</button>

    @if (catalogConfig().showBreadcrumbs && breadcrumb().length > 0) {
      <app-breadcrumb
        [rootLabel]="'catalog.allCategories' | translate"
        [ariaLabel]="'catalog.breadcrumb' | translate"
        [items]="breadcrumbItems()"
        (rootClick)="browseCategories()"
        (itemClick)="onBreadcrumbItemClick($event)" />
    }

    <app-catalog-search-box
      [query]="state().search"
      [loading]="loadingProducts()"
      [suggestions]="searchSuggestions()"
      [recentSearches]="recentSearches()"
      [popularSearches]="popularSearches()"
      [searchHistory]="searchHistory()"
      [noResults]="noResults()"
      (queryChange)="onSearchQueryChange($event)"
      (searchSubmit)="submitSearch($event)"
      (suggestionSelected)="useSuggestion($event)"
      (recentSelected)="useRecentSearch($event)"
      (historyCleared)="clearSearchHistory()" />

    @if (userExperienceConfig().savedSearches.enabled && savedSearches().length > 0) {
      <div class="catalog-saved-searches">
        @for (saved of savedSearches(); track saved.id) {
          <div class="catalog-saved-chip">
            <button type="button" (click)="useSavedSearch(saved.id)">{{ saved.name }}</button>
            <button type="button" class="catalog-saved-chip-remove" [attr.aria-label]="'catalog.removeSavedSearch' | translate" (click)="removeSavedSearch(saved.id)"><app-icon name="x" [size]="14" /></button>
          </div>
        }
      </div>
    }
  </header>

  @if (loading()) {
    <section class="catalog-loading" [attr.aria-label]="'catalog.loading' | translate" aria-busy="true">
      @for (slot of skeletonSlots; track $index) {
        <div class="catalog-skeleton-card">
          <app-skeleton shape="rect" class="catalog-skeleton-image" height="auto" />
          <app-skeleton shape="text" width="72%" height="18px" />
          <app-skeleton shape="text" height="14px" />
        </div>
      }
    </section>
  }

  @if (error()) {
    <section class="catalog-message catalog-message-error">
      <app-empty-state [title]="'catalog.errorTitle' | translate" [description]="error()! | translate">
        <span slot="icon" class="catalog-message-error__icon" aria-hidden="true">!</span>
        <div slot="actions">
          <app-button variant="primary" (click)="retry()">{{ 'catalog.retry' | translate }}</app-button>
        </div>
      </app-empty-state>
    </section>
  }

  @if (!loading() && !error() && viewMode() === 'categories') {
    <section class="catalog-section">
      <div class="catalog-section-heading">
        <h1>{{ state().category?.title || ('catalog.allCategories' | translate) }}</h1>
        <p>{{ 'catalog.categoryHint' | translate }} • {{ 'catalog.entriesCount' | translate:{ count: categories().length } }}</p>
      </div>

      @if (catalogConfig().showCategoryBanner) {
        <div class="catalog-category-banner card">
          <h3>{{ state().category?.title || ('catalog.allCategories' | translate) }}</h3>
          <p>{{ 'catalog.categoryBannerPlaceholder' | translate }}</p>
        </div>
      }

      @if (catalogConfig().showSubcategoryChips && subcategoryChips().length > 0) {
        <div class="subcategory-chips">
          @for (subcategory of subcategoryChips(); track subcategory.id) {
            <button type="button" class="subcategory-chip" (click)="selectCategory(subcategory)">
              {{ subcategory.title }}
            </button>
          }
        </div>
      }

      @if (categories().length > 0) {
        <app-catalog-category-grid [categories]="categories()" (categorySelected)="selectCategory($event)" />
      } @else {
        <div class="catalog-message">
          <app-empty-state [title]="'catalog.emptyTitle' | translate" [description]="'catalog.emptyCategories' | translate" />
        </div>
      }
    </section>
  }

  @if (!loading() && !error() && viewMode() === 'products') {
    <section class="catalog-section catalog-products-section">
      @if (showDesktopFilters()) {
        <aside class="catalog-left-panel" [attr.aria-label]="'catalog.filtersPanelAria' | translate">
          <app-catalog-filters-panel
            [definitions]="filterDefinitions()"
            [state]="filterState()"
            (stateChange)="onFilterStateChange($event)" />
        </aside>
      }

      <div class="catalog-results-panel">
        @if (showMobileToolbar()) {
          <div class="catalog-mobile-toolbar" [attr.aria-label]="'catalog.mobileToolbarAria' | translate">
            <button type="button" class="catalog-mobile-toolbar-btn" [attr.aria-label]="'catalog.filtersTitle' | translate" (click)="openFilterDrawer()">{{ 'catalog.filtersTitle' | translate }}</button>
            <button type="button" class="catalog-mobile-toolbar-btn" [attr.aria-label]="'catalog.sortBy' | translate" (click)="openSortSheet()">{{ 'catalog.sortBy' | translate }}</button>
            <button type="button" class="catalog-mobile-toolbar-btn" [attr.aria-label]="'catalog.gridCycle' | translate" (click)="openGridSheet()">{{ 'catalog.gridCycle' | translate }}</button>
          </div>
        }

        @if (showCatalogTools()) {
          <div class="catalog-tools-row">
            <div class="catalog-sort-reset-group">
              @if (isDrawerLayout() && !isMobile()) {
                <button type="button" class="catalog-reset-btn" (click)="openFilterDrawer()">{{ 'catalog.filtersTitle' | translate }}</button>
              }

              @if (!isMobile()) {
                <app-catalog-sorting-control
                  [options]="sortDefinitions()"
                  [selected]="state().sort"
                  (selectedChange)="changeSort($event)" />
              }

              <button type="button" class="catalog-reset-btn" (click)="resetFilters()">{{ 'catalog.resetFilters' | translate }}</button>
            </div>

            @if (userExperienceConfig().savedSearches.enabled) {
              <button type="button" class="catalog-save-search-btn" (click)="saveCurrentSearch()">{{ 'ux.saveSearch' | translate }}</button>
            }

            @if (!isMobile()) {
              <app-catalog-layout-switcher
                [active]="state().layout"
                [available]="availableLayouts"
                (activeChange)="changeLayout($event)" />
            }
          </div>
        }

        @if (catalogConfig().navigationMode !== 'default') {
          <div class="catalog-navigation-placeholder card">
            <strong>{{ catalogConfig().navigationMode }}</strong>
            <p>{{ 'catalog.navigationPlaceholder' | translate }}</p>
          </div>
        }

        @if (offlineState()) {
          <div class="catalog-message">
            <app-empty-state [title]="'catalog.offlineTitle' | translate" [description]="'catalog.offlineMessage' | translate" />
          </div>
        } @else if (loadingProducts()) {
          <app-catalog-search-results
            [products]="[]"
            [total]="state().pagination.total"
            [page]="state().pagination.page"
            [pageSize]="state().pagination.count"
            [summary]="searchSummary()"
            [loading]="true"
            [loadingStrategy]="loadingStrategy()"
            [hasMore]="state().pagination.hasMore"
            [layout]="state().layout"
            [showRatings]="features().ratings"
            [showDiscounts]="features().discounts"
            [showAvailability]="features().availability"
            [showShareAction]="features().share"
            [favoriteIds]="favoriteIds()"
            [comparedIds]="comparedIds()"
            [searchQuery]="state().search"
            [queryTooShort]="isQueryTooShort()"
            [minSearchLength]="minSearchLength" />
        } @else if (isEmptyCategoryState()) {
          <app-catalog-empty-state
            variant="category"
            [title]="'catalog.emptyCategoryTitle' | translate"
            [categoryTitle]="state().category?.title ?? null"
            [message]="'catalog.emptyCategoryMessage' | translate"
            [actionLabel]="'catalog.browseCategories' | translate"
            [secondaryActionLabel]="'catalog.goToParentCategory' | translate"
            (action)="browseCategories()"
            (secondaryAction)="goToParentCategory()" />
        } @else if (isFilteredEmptyState()) {
          <app-catalog-empty-state
            variant="filtered"
            [title]="'catalog.noFilterMatchTitle' | translate"
            [message]="'catalog.noFilterMatchMessage' | translate"
            [actionLabel]="'catalog.clearFilters' | translate"
            [popularCategories]="popularCategorySuggestions()"
            [popularSearches]="popularSearches()"
            [recommendedProducts]="recommendedProductsForEmpty()"
            (action)="resetFilters()"
            (popularCategorySelected)="usePopularCategory($event)"
            (popularSearchSelected)="useRecentSearch($event)"
            (recommendedProductSelected)="selectProduct($event)"
            (recommendedAddToCart)="addRecommendedToCart($event)" />

          @if (isDrawerLayout()) {
            <button type="button" class="catalog-open-filters-btn" (click)="openFilterDrawer()">{{ 'catalog.openFilters' | translate }}</button>
          }
        } @else {
          <app-catalog-search-results
            [products]="products()"
            [total]="state().pagination.total"
            [page]="state().pagination.page"
            [pageSize]="state().pagination.count"
            [summary]="searchSummary()"
            [loading]="false"
            [loadingStrategy]="loadingStrategy()"
            [hasMore]="state().pagination.hasMore"
            [layout]="state().layout"
            [showRatings]="features().ratings"
            [showDiscounts]="features().discounts"
            [showAvailability]="features().availability"
            [showShareAction]="features().share"
            [favoriteIds]="favoriteIds()"
            [comparedIds]="comparedIds()"
            [searchQuery]="state().search"
            [queryTooShort]="isQueryTooShort()"
            [minSearchLength]="minSearchLength"
            (pageChange)="onResultsPageChange($event)"
            (loadMore)="loadNextPage()"
            (productSelected)="selectProduct($event)"
            (addToCart)="addToCart($event)"
            (productPreview)="previewProduct($event)"
            (quickView)="openQuickView($event)"
            (favoriteToggled)="onFavoriteToggled($event)"
            (compareToggled)="onCompareToggled($event)"
            (shareRequested)="onShareRequested($event)" />
        }
      </div>
    </section>

    @if (isDrawerLayout() && filterDrawerOpen()) {
      <div class="catalog-overlay" (click)="closeFilterDrawer()" aria-hidden="true"></div>
      <aside class="catalog-filter-drawer" role="dialog" [attr.aria-label]="'catalog.filtersDrawerAria' | translate" aria-modal="true" cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
        <header class="catalog-filter-drawer-head">
          <h2>{{ 'catalog.filtersTitle' | translate }}</h2>
          <button type="button" class="catalog-icon-btn" [attr.aria-label]="'catalog.close' | translate" (click)="closeFilterDrawer()"><app-icon name="x" [size]="18" /></button>
        </header>

        <div class="catalog-filter-drawer-body">
          <app-catalog-filters-panel
            [definitions]="filterDefinitions()"
            [state]="filterState()"
            (stateChange)="onFilterStateChange($event)" />
        </div>

        <footer class="catalog-filter-drawer-actions">
          <button type="button" class="catalog-reset-btn" (click)="resetFilters()">{{ 'catalog.resetFilters' | translate }}</button>
          <button type="button" class="catalog-apply-btn" (click)="applyFilterDrawer()">{{ 'catalog.applyFilters' | translate }}</button>
        </footer>
      </aside>
    }

    @if (isMobile() && sortSheetOpen()) {
      <div class="catalog-overlay" (click)="closeSortSheet()" aria-hidden="true"></div>
      <section class="catalog-sort-sheet" role="dialog" [attr.aria-label]="'catalog.sortSheetAria' | translate" aria-modal="true" cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
        <header class="catalog-sort-sheet-head">
          <h2>{{ 'catalog.sortBy' | translate }}</h2>
          <button type="button" class="catalog-icon-btn" [attr.aria-label]="'catalog.close' | translate" (click)="closeSortSheet()"><app-icon name="x" [size]="18" /></button>
        </header>

        <div class="catalog-sort-sheet-options">
          @for (option of mobileSortOptions(); track option.id) {
            <button type="button" class="catalog-sort-option" [class.active]="state().sort === option.id" [attr.aria-current]="state().sort === option.id ? 'true' : null" (click)="selectSortFromSheet(option.id)">
              {{ option.label }}
            </button>
          }
        </div>
      </section>
    }

    @if (isMobile() && gridSheetOpen()) {
      <div class="catalog-overlay" (click)="closeGridSheet()" aria-hidden="true"></div>
      <section class="catalog-sort-sheet catalog-grid-sheet" role="dialog" [attr.aria-label]="'catalog.gridCycle' | translate" aria-modal="true" cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
        <header class="catalog-sort-sheet-head">
          <h2>{{ 'catalog.gridCycle' | translate }}</h2>
          <button type="button" class="catalog-icon-btn" [attr.aria-label]="'catalog.close' | translate" (click)="closeGridSheet()"><app-icon name="x" [size]="18" /></button>
        </header>

        <div class="catalog-sort-sheet-options">
          @for (layout of availableLayouts; track layout) {
            <button type="button" class="catalog-sort-option" [class.active]="state().layout === layout" [attr.aria-current]="state().layout === layout ? 'true' : null" (click)="selectLayoutFromSheet(layout)">
              {{ layoutLabelKey(layout) | translate }}
            </button>
          }
        </div>
      </section>
    }
  }
</main>

<app-quick-view-dialog
  [product]="quickViewProduct()"
  [loading]="quickViewLoading()"
  (closed)="closeQuickView()"
  (addToCart)="addQuickViewToCart($event)" />
