<?php
/**
 * TitanCart shop archive — ShopNest offcanvas filter layout.
 *
 * Override: {theme}/titancart/shop/archive.php
 *
 * @var array  $products      Product rows from the DB
 * @var array  $params        Pagination info
 * @var object $category      Current category (null on shop index)
 * @var int    $category_id   Current category ID (0 = all)
 * @var bool   $is_shortcode  True when via [titancart_shop]
 * @package TitanCart
 */

defined( 'ABSPATH' ) || exit;

$products     = $products     ?? [];
$params       = $params       ?? [ 'page' => 1, 'total_items' => 0, 'total_pages' => 1 ];
$category     = $category     ?? null;
$category_id  = $category_id  ?? 0;
$tag          = ( isset( $tag ) && is_object( $tag ) && ! empty( $tag->name ) ) ? $tag : null; // hard guard against WP template-loader.php's foreach `$tag` leak (S123)
$is_shortcode = $is_shortcode ?? false;
$filter_mode  = $filter_mode  ?? sanitize_key( $_GET['filter'] ?? '' );
$currency     = apply_filters( 'titancart_currency_symbol', '$' );

// ── Build sort options from Settings → Appearance ─────────────────────
$_ss = \TitanCart\Services\SettingsService::class;
$sort_map = [
    'sort_bestselling'   => [ 'value' => 'sales-desc',   'label' => __( 'Best Selling', 'titancart-lite' ) ],
    'sort_newest'        => [ 'value' => 'date-desc',    'label' => __( 'New Arrivals', 'titancart-lite' ) ],
    'sort_oldest'        => [ 'value' => 'date-asc',     'label' => __( 'Oldest First', 'titancart-lite' ) ],
    'sort_popularity'    => [ 'value' => 'rating-desc',  'label' => __( 'Top Rated', 'titancart-lite' ) ],
    'sort_price_low'     => [ 'value' => 'price-asc',    'label' => __( 'Price: Low to High', 'titancart-lite' ) ],
    'sort_price_high'    => [ 'value' => 'price-desc',   'label' => __( 'Price: High to Low', 'titancart-lite' ) ],
    'sort_alpha_az'      => [ 'value' => 'name-asc',     'label' => __( 'Name: A–Z', 'titancart-lite' ) ],
    'sort_alpha_za'      => [ 'value' => 'name-desc',    'label' => __( 'Name: Z–A', 'titancart-lite' ) ],
    'sort_discount_high' => [ 'value' => 'discount-desc', 'label' => __( 'Biggest Discount', 'titancart-lite' ) ],
    'sort_discount_low'  => [ 'value' => 'discount-asc',  'label' => __( 'Smallest Discount', 'titancart-lite' ) ],
];
$sort_options  = [];
foreach ( $sort_map as $setting_key => $opt ) {
    if ( $_ss::bool( 'appearance', $setting_key, in_array( $setting_key, [ 'sort_newest', 'sort_alpha_az', 'sort_price_low', 'sort_price_high', 'sort_popularity', 'sort_bestselling' ], true ) ) ) {
        $sort_options[] = $opt;
    }
}
// Fallback — always show at least New Arrivals.
if ( empty( $sort_options ) ) {
    $sort_options[] = [ 'value' => 'date-desc', 'label' => __( 'New Arrivals', 'titancart-lite' ) ];
}
// Default sort from settings.
$default_sort_map = [
    'newest'      => 'date-desc',   'oldest'     => 'date-asc',
    'alpha_az'    => 'name-asc',    'alpha_za'   => 'name-desc',
    'price_low'   => 'price-asc',   'price_high' => 'price-desc',
    'popularity'  => 'rating-desc', 'bestselling' => 'sales-desc',
];
$default_sort_key = $_ss::get( 'appearance', 'product_list_default_sort', 'alpha_az' );
$default_sort     = $default_sort_map[ $default_sort_key ] ?? 'date-desc';
$grid_columns     = $_ss::int( 'appearance', 'columns_in_product_list', 4 );
$pag_type         = $_ss::get( 'appearance', 'pagination_type', 'numbers' );

// ── View mode settings ──────────────────────────────────────────────
$view_grid    = $_ss::bool( 'appearance', 'view_grid_enabled', true );
$view_list    = $_ss::bool( 'appearance', 'view_list_enabled', true );
$view_compact = $_ss::bool( 'appearance', 'view_compact_enabled', false );
$default_view = $_ss::get( 'appearance', 'product_list_default_view', 'grid' );
// Ensure default view is actually enabled; fallback to first enabled.
$enabled_views = [];
if ( $view_grid )    $enabled_views[] = 'grid';
if ( $view_list )    $enabled_views[] = 'list';
if ( $view_compact ) $enabled_views[] = 'compact';
if ( empty( $enabled_views ) ) $enabled_views[] = 'grid'; // always at least one
if ( ! in_array( $default_view, $enabled_views, true ) ) $default_view = $enabled_views[0];
$allow_compare = $_ss::bool( 'general', 'catalog_allow_compare', true );

// Filter-mode page titles & descriptions
$filter_meta = [
    'hidden-treasures' => [
        'title' => __( 'Hidden Treasures', 'titancart-lite' ),
        'desc'  => __( 'These products have secret cart discounts — add to cart to reveal your savings!', 'titancart-lite' ),
        'icon'  => 'bi-gift',
        'color' => '#d97706',
    ],
    'biggest-deals' => [
        'title' => __( 'Biggest Deals', 'titancart-lite' ),
        'desc'  => __( 'Our largest markdowns, sorted by biggest discount first.', 'titancart-lite' ),
        'icon'  => 'bi-tag',
        'color' => '#16a34a',
    ],
    'member-deals' => [
        'title' => __( 'Member Exclusive Deals', 'titancart-lite' ),
        'desc'  => __( 'Coming soon — join our membership for special pricing!', 'titancart-lite' ),
        'icon'  => 'bi-gem',
        'color' => '#2563eb',
    ],
];
$active_filter = $filter_meta[ $filter_mode ] ?? null;
// Page title precedence: filter-mode landing > tag archive > category > shop default.
if ( $active_filter ) {
    $page_title = $active_filter['title'];
} elseif ( $tag ) {
    /* translators: %s = tag name */
    $page_title = sprintf( __( 'Products tagged "%s"', 'titancart-lite' ), $tag->name );
} elseif ( $category ) {
    $page_title = $category->name;
} else {
    $page_title = __( 'Shop', 'titancart-lite' );
}

/**
 * Filter the shop archive banner heading.
 *
 * Lets a theme or preset retitle the page-header banner — e.g. a marketplace
 * preset replacing the default "Shop" with custom copy — without overriding the
 * dynamic category / tag / filter titles unless it chooses to. The $ctx array
 * lets callbacks target only the bare shop index.
 *
 * @param string $page_title Resolved heading.
 * @param array  $ctx        Context: is_index (bool), category, tag, filter_mode.
 */
$page_title = (string) apply_filters( 'titancart_shop_banner_title', $page_title, [
    'is_index'    => ( ! $active_filter && ! $tag && ! $category ),
    'category'    => $category,
    'tag'         => $tag,
    'filter_mode' => $filter_mode,
] );

if ( ! $is_shortcode ) { get_header(); }

// ── Banner data (used by both theme and plugin versions) ──
$banner_classes = 'tc-shop__banner';
$banner_style   = '';
$banner_overlay = '';
$banner_is_theme = defined( 'TITANCART_THEME_ACTIVE' );

if ( $banner_is_theme ) {
    $banner_classes .= ' tc-shop__banner--theme';
    $banner_image_id      = get_theme_mod( 'tct_shop_banner_image' );
    $banner_image_dark_id = get_theme_mod( 'tct_shop_banner_image_dark' );
    $banner_overlay       = get_theme_mod( 'tct_shop_banner_overlay', 'rgba(0,0,0,0.45)' );
    $banner_height        = get_theme_mod( 'tct_shop_banner_height', 280 );
    $banner_position      = get_theme_mod( 'tct_shop_banner_position', 'center center' );

    if ( $banner_image_id ) {
        $banner_url      = wp_get_attachment_image_url( (int) $banner_image_id, 'full' );
        $banner_url_dark = $banner_image_dark_id ? wp_get_attachment_image_url( (int) $banner_image_dark_id, 'full' ) : '';
        if ( $banner_url ) {
            $banner_style = sprintf(
                'background-image:url(%s);background-size:cover;background-position:%s;height:%dpx;',
                esc_url( $banner_url ),
                esc_attr( $banner_position ),
                (int) $banner_height
            );
            $banner_classes .= ' tc-shop__banner--has-image';
            // Optional dark-mode banner: when the user sets BOTH a light and
            // dark banner image in the Customizer, store the dark URL in a
            // CSS custom property on this section. shop.css swaps
            // `background-image` to that variable when [data-theme="dark"]
            // is active. Inline style is required because the light URL is
            // also inline (otherwise specificity wouldn't match).
            if ( $banner_url_dark ) {
                $banner_style   .= sprintf( '--tc-banner-img-dark:url(%s);', esc_url( $banner_url_dark ) );
                $banner_classes .= ' tc-shop__banner--has-dark-image';
            }
        }
    }
}
?>

<?php if ( $banner_is_theme ) : ?>
<!-- ═══ Full-Width Page Header Banner (Theme) ═══ -->
<section class="<?php echo esc_attr( $banner_classes ); ?>" style="<?php echo esc_attr( $banner_style ); ?>">
  <?php if ( strpos( $banner_classes, '--has-image' ) !== false ) : ?>
  <div class="tc-shop__banner-overlay" style="background:<?php echo esc_attr( $banner_overlay ); ?>;position:absolute;top:0;left:0;right:0;bottom:0;"></div>
  <?php endif; ?>
  <div class="tc-shop__banner-inner">
    <h2 class="tc-shop__banner-title"><?php echo esc_html( $page_title ); ?></h2>
    <nav class="tc-breadcrumb tc-breadcrumb--centered" aria-label="Breadcrumb">
      <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
      <i class="bi bi-chevron-right"></i>
      <?php if ( $category ) : ?>
        <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
        <i class="bi bi-chevron-right"></i>
        <span class="tc-breadcrumb__current"><?php echo esc_html( $category->name ); ?></span>
      <?php elseif ( $tag ) : ?>
        <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
        <i class="bi bi-chevron-right"></i>
        <span class="tc-breadcrumb__current"><?php echo esc_html( sprintf( /* translators: %s = tag name */ __( 'Tag: %s', 'titancart-lite' ), $tag->name ) ); ?></span>
      <?php elseif ( $active_filter ) : ?>
        <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
        <i class="bi bi-chevron-right"></i>
        <span class="tc-breadcrumb__current"><?php echo esc_html( $active_filter['title'] ); ?></span>
      <?php else : ?>
        <span class="tc-breadcrumb__current">Shop</span>
      <?php endif; ?>
    </nav>
  </div>
</section>
<?php endif; ?>

<div class="tc-shop" id="tc-shop-app"
     data-api="<?php echo esc_url( rest_url( 'titancart/v1/store' ) ); ?>"
     data-category="<?php echo esc_attr( $category_id ); ?>"
     data-tag-slug="<?php echo esc_attr( $tag->slug ?? '' ); ?>"
     data-symbol="<?php echo esc_attr( $currency ); ?>"
     data-filter="<?php echo esc_attr( $filter_mode ); ?>"
     data-enable-qv="<?php echo \TitanCart\Services\SettingsService::bool( 'appearance', 'enable_quick_view', true ) ? '1' : '0'; ?>"
     data-default-sort="<?php echo esc_attr( $default_sort ); ?>"
     data-grid-cols="<?php echo esc_attr( $grid_columns ); ?>"
     data-default-view="<?php echo esc_attr( $default_view ); ?>"
     data-views="<?php echo esc_attr( implode( ',', $enabled_views ) ); ?>"
     data-allow-compare="<?php echo $allow_compare ? '1' : '0'; ?>"
data-wishlist-on="<?php echo \TitanCart\REST\Extensions\ExtensionsController::is_active( 'wishlist' ) ? '1' : '0'; ?>"
     data-total-pages="<?php echo (int) $params['total_pages']; ?>"
     style="--tc-grid-cols: <?php echo (int) $grid_columns; ?>">

  <?php if ( ! $banner_is_theme ) : ?>
  <!-- ═══ Page Header Banner (Plugin — inside container) ═══ -->
  <section class="tc-shop__banner">
    <div class="tc-shop__banner-inner">
      <h2 class="tc-shop__banner-title"><?php echo esc_html( $page_title ); ?></h2>
      <nav class="tc-breadcrumb tc-breadcrumb--centered" aria-label="Breadcrumb">
        <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
        <i class="bi bi-chevron-right"></i>
        <?php if ( $category ) : ?>
          <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
          <i class="bi bi-chevron-right"></i>
          <span class="tc-breadcrumb__current"><?php echo esc_html( $category->name ); ?></span>
        <?php elseif ( $tag ) : ?>
          <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
          <i class="bi bi-chevron-right"></i>
          <span class="tc-breadcrumb__current"><?php echo esc_html( sprintf( /* translators: %s = tag name */ __( 'Tag: %s', 'titancart-lite' ), $tag->name ) ); ?></span>
        <?php elseif ( $active_filter ) : ?>
          <a href="<?php echo esc_url( titancart_shop_url() ); ?>">Shop</a>
          <i class="bi bi-chevron-right"></i>
          <span class="tc-breadcrumb__current"><?php echo esc_html( $active_filter['title'] ); ?></span>
        <?php else : ?>
          <span class="tc-breadcrumb__current">Shop</span>
        <?php endif; ?>
      </nav>
    </div>
  </section>
  <?php endif; ?>

  <?php if ( $active_filter ) : ?>
  <!-- ═══ Filter Mode Banner ═══ -->
  <div class="tc-filter-banner" style="background:<?php echo esc_attr( $active_filter['color'] ); ?>10; border-left:4px solid <?php echo esc_attr( $active_filter['color'] ); ?>; padding:16px 24px; border-radius:8px; margin:20px 0 0; display:flex; align-items:center; gap:14px;">
    <i class="bi <?php echo esc_attr( $active_filter['icon'] ); ?>" style="font-size:24px; color:<?php echo esc_attr( $active_filter['color'] ); ?>;"></i>
    <div>
      <p style="margin:0; font-size:14px; color:#333; font-weight:500;"><?php echo esc_html( $active_filter['desc'] ); ?></p>
    </div>
  </div>
  <?php endif; ?>

  <!-- ═══ Shop Content ═══ -->
  <section class="tc-shop__content">

    <!-- Filter toggle (fixed left edge, rotated — ShopNest style) -->
    <button class="tc-shop__filter-toggle" id="tc-filter-toggle" type="button">
      <i class="bi bi-funnel"></i>
      <span>Filter</span>
    </button>

    <!-- ═══ Offcanvas Filter Panel ═══ -->
    <div class="tc-offcanvas-overlay" id="tc-filter-overlay" hidden></div>
    <aside class="tc-offcanvas" id="tc-filter-panel" aria-label="Filters">
      <div class="tc-offcanvas__header">
        <h5 class="tc-offcanvas__title">Filter</h5>
        <button class="tc-offcanvas__close" id="tc-filter-close" type="button" aria-label="Close">
          <i class="bi bi-x-lg"></i>
        </button>
      </div>
      <div class="tc-offcanvas__body" id="tc-filter-body">
        <!-- Active filter chips card -->
        <div class="tc-filter-card" id="tc-active-card" hidden>
          <div class="tc-filter-card__header">
            <h6>Filter</h6>
            <a href="#" class="tc-filter-card__clear" id="tc-active-clear">Clear all</a>
          </div>
          <div class="tc-filter-card__chips" id="tc-active-filters"></div>
        </div>

        <!-- JS populates filter section cards here from /store/filters API -->
        <div class="tc-offcanvas__loading" id="tc-filter-loading">
          <div class="tc-spinner"></div>
          <span>Loading filters…</span>
        </div>
      </div>
      <div class="tc-offcanvas__footer">
        <button class="tc-btn tc-btn--outline tc-btn--sm" id="tc-filter-clear" type="button">Clear All</button>
        <button class="tc-btn tc-btn--primary tc-btn--sm" id="tc-filter-apply" type="button">Apply Filters</button>
      </div>
    </aside>

    <!-- ═══ Products Area ═══ -->
    <div class="tc-shop__products">

      <!-- Toolbar -->
      <div class="tc-shop__toolbar">
        <p class="tc-shop__found">Found <strong id="tc-product-count"><?php echo (int) $params['total_items']; ?></strong> items</p>
        <div class="tc-shop__sort">
          <span class="tc-shop__sort-label">Sort by:</span>
          <div class="tc-shop__sort-dropdown">
            <select class="tc-shop__sort-select" id="tc-sort">
              <?php foreach ( $sort_options as $opt ) : ?>
                <option value="<?php echo esc_attr( $opt['value'] ); ?>"<?php echo $opt['value'] === $default_sort ? ' selected' : ''; ?>><?php echo esc_html( $opt['label'] ); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <?php if ( count( $enabled_views ) > 1 ) : ?>
        <div class="tc-shop__view-toggle" id="tc-view-toggle">
          <?php if ( $view_grid ) : ?>
          <button type="button" class="tc-shop__view-btn<?php echo $default_view === 'grid' ? ' tc-shop__view-btn--active' : ''; ?>" data-view="grid" title="Grid view">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1" y="1" width="6" height="6" rx="1"/><rect x="9" y="1" width="6" height="6" rx="1"/><rect x="1" y="9" width="6" height="6" rx="1"/><rect x="9" y="9" width="6" height="6" rx="1"/></svg>
          </button>
          <?php endif; ?>
          <?php if ( $view_list ) : ?>
          <button type="button" class="tc-shop__view-btn<?php echo $default_view === 'list' ? ' tc-shop__view-btn--active' : ''; ?>" data-view="list" title="List view">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1" y="1.5" width="4" height="4" rx="1"/><line x1="7" y1="3.5" x2="15" y2="3.5"/><rect x="1" y="7.5" width="4" height="4" rx="1"/><line x1="7" y1="9.5" x2="15" y2="9.5"/></svg>
          </button>
          <?php endif; ?>
          <?php if ( $view_compact ) : ?>
          <button type="button" class="tc-shop__view-btn<?php echo $default_view === 'compact' ? ' tc-shop__view-btn--active' : ''; ?>" data-view="compact" title="Compact list">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><line x1="1" y1="2.5" x2="15" y2="2.5"/><line x1="1" y1="6" x2="15" y2="6"/><line x1="1" y1="9.5" x2="15" y2="9.5"/><line x1="1" y1="13" x2="15" y2="13"/></svg>
          </button>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>

      <?php
      // Top pagination — only for numbered pages mode.
      $pagination_on_top = \TitanCart\Services\SettingsService::bool( 'appearance', 'pagination_on_top', false );
      if ( $pagination_on_top && $pag_type === 'numbers' && (int) $params['total_pages'] > 1 ) :
          $current = (int) $params['page'];
          $total   = (int) $params['total_pages'];
      ?>
      <nav class="tc-pagination tc-pagination--top" id="tc-pagination-top" style="margin-bottom:16px">
        <a href="#" class="tc-pagination__item" data-page="<?php echo (int) max( 1, $current - 1 ); ?>"><i class="bi bi-chevron-double-left"></i></a>
        <?php for ( $i = 1; $i <= $total; $i++ ) :
            $cls = $i === $current ? 'tc-pagination__item tc-pagination__item--active' : 'tc-pagination__item';
        ?>
            <a href="#" class="<?php echo esc_attr( $cls ); ?>" data-page="<?php echo (int) $i; ?>"><?php echo (int) $i; ?></a>
        <?php endfor; ?>
        <a href="#" class="tc-pagination__item" data-page="<?php echo (int) min( $total, $current + 1 ); ?>"><i class="bi bi-chevron-double-right"></i></a>
      </nav>
      <?php endif; ?>

      <!-- Product Grid -->
      <div class="tc-product-grid" id="tc-product-grid">
        <?php if ( ! empty( $products ) ) : ?>
          <?php foreach ( $products as $product ) :
            \TitanCart\Storefront\TemplateLoader::get_template( 'product/card.php', compact( 'product' ) );
          endforeach; ?>
        <?php else : ?>
          <div class="tc-shop__empty" id="tc-empty-state">
            <i class="bi bi-box-seam" style="font-size:48px;color:#d4d4d4"></i>
            <p><?php esc_html_e( 'No products found.', 'titancart-lite' ); ?></p>
            <p class="tc-muted"><?php esc_html_e( 'Try adjusting your filters or browse all products.', 'titancart-lite' ); ?></p>
          </div>
        <?php endif; ?>
      </div>

      <!-- Pagination -->
      <?php if ( (int) $params['total_pages'] > 1 ) : ?>
        <?php if ( $pag_type === 'load_more' ) : ?>
          <nav class="tc-pagination" id="tc-pagination">
            <button type="button" class="tc-pagination__load-more" id="tc-load-more">Load more products</button>
          </nav>
        <?php elseif ( $pag_type === 'infinite_scroll' ) : ?>
          <nav class="tc-pagination" id="tc-pagination">
            <div class="tc-pagination__scroll-sentinel" id="tc-scroll-sentinel"><div class="tc-spinner tc-spinner--sm"></div></div>
          </nav>
        <?php else : ?>
          <nav class="tc-pagination" id="tc-pagination">
            <?php
            $current = (int) $params['page'];
            $total   = (int) $params['total_pages'];
            ?>
            <a href="#" class="tc-pagination__item" data-page="<?php echo (int) max( 1, $current - 1 ); ?>"><i class="bi bi-chevron-double-left"></i></a>
            <?php for ( $i = 1; $i <= $total; $i++ ) :
              $cls = $i === $current ? 'tc-pagination__item tc-pagination__item--active' : 'tc-pagination__item';
            ?>
              <a href="#" class="<?php echo esc_attr( $cls ); ?>" data-page="<?php echo (int) $i; ?>"><?php echo (int) $i; ?></a>
            <?php endfor; ?>
            <a href="#" class="tc-pagination__item" data-page="<?php echo (int) min( $total, $current + 1 ); ?>"><i class="bi bi-chevron-double-right"></i></a>
          </nav>
        <?php endif; ?>
      <?php endif; ?>

    </div><!-- .tc-shop__products -->

  </section>

  <!-- Loading overlay -->
  <div class="tc-shop__loading" id="tc-loading" hidden>
    <div class="tc-spinner tc-spinner--lg"></div>
  </div>

</div>

<?php if ( ! $is_shortcode ) { get_footer(); }
