<?php
defined('ABSPATH') || exit;

get_header();

$shop_url = get_permalink(wc_get_page_id('shop'));
$shop_query = $GLOBALS['wp_query'] ?? null;
?>

<main class="fjord-main fjord-shop">
  <?php
  $shop_title = get_theme_mod('fjord_shop_title', 'Shop');
  $shop_lead = get_theme_mod('fjord_shop_lead', 'Explore our Dark Collection, where deep hues and refined finishes bring an air of sophistication and drama to any room.');
  ?>
  <section class="fjord-shop__intro">
    <?php
    if (function_exists('woocommerce_breadcrumb')) {
      woocommerce_breadcrumb([
        'delimiter' => '<span class="fjord-blog-post__breadcrumb-sep">/</span>',
        'wrap_before' => '<nav class="fjord-blog-post__breadcrumb" aria-label="Breadcrumb">',
        'wrap_after' => '</nav>',
        'before' => '',
        'after' => '',
      ]);
    }
    ?>
    <h1 class="fjord-shop__title"><?php echo esc_html($shop_title); ?></h1>
    <p class="fjord-shop__lead"><?php echo esc_html($shop_lead); ?></p>
  </section>

  <section class="fjord-shop__filters" data-shop-filters>
    <button class="fjord-shop__filter fjord-shop__filter--icon" type="button" data-filter-drawer-open aria-label="Open filters">→</button>
    <?php
    $categories = get_terms([
      'taxonomy' => 'product_cat',
      'hide_empty' => false,
      'exclude' => [get_option('default_product_cat')],
    ]);

    if (!is_wp_error($categories) && !empty($categories)) {
      foreach ($categories as $category) {
        $link = get_term_link($category);
        if (is_wp_error($link)) {
          continue;
        }
        printf(
          '<a class="fjord-shop__filter" href="%s"><span class="fjord-shop__filter-label">%s</span></a>',
          esc_url($link),
          esc_html($category->name)
        );
      }
    }
    ?>
  </section>

  <?php
  $filter_args = $_GET;
  unset($filter_args['paged'], $filter_args['page']);
  $shop_base = $shop_url ?: home_url('/tienda/');
  $attribute_taxonomies = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : [];
  $is_filtered = !empty($filter_args);
  $max_price_product = function_exists('wc_get_products') ? wc_get_products([
    'limit' => 1,
    'status' => 'publish',
    'orderby' => 'price',
    'order' => 'DESC',
    'return' => 'ids',
  ]) : [];
  $max_price = 0;
  if (!empty($max_price_product)) {
    $product = wc_get_product($max_price_product[0]);
    if ($product) {
      $max_price = (float) $product->get_price();
    }
  }
  $max_price = max(1, $max_price);
  $min_price_value = isset($_GET['min_price']) ? max(0, (float) $_GET['min_price']) : 0;
  $min_price_value = min($min_price_value, $max_price);
  $max_price_value = isset($_GET['max_price']) ? max($min_price_value, (float) $_GET['max_price']) : $max_price;
  $max_price_value = min($max_price_value, $max_price);
  $currency_symbol = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$';
  $price_decimals = function_exists('wc_get_price_decimals') ? wc_get_price_decimals() : 0;
  ?>

  <?php
  $paged = max(1, (int) get_query_var('paged'), (int) get_query_var('page'));
  $query_vars = $shop_query ? $shop_query->query_vars : [];
  ?>

  <?php if (wc_get_loop_prop('total')) : ?>
    <section
      class="fjord-shop__grid"
      data-shop-grid
      data-shop-page="<?php echo esc_attr($paged); ?>"
      data-shop-max="<?php echo esc_attr($shop_query ? $shop_query->max_num_pages : 1); ?>"
      data-shop-query="<?php echo esc_attr(wp_json_encode($query_vars)); ?>"
    >
      <?php while (have_posts()) : ?>
        <?php the_post(); ?>
        <?php wc_get_template_part('content', 'product'); ?>
      <?php endwhile; ?>
    </section>
    <button class="fjord-shop__load-more" type="button" data-shop-load>
      Ver más
    </button>
  <?php else : ?>
    <p class="fjord-shop__empty"><?php esc_html_e('No products found.', 'fjord-clone'); ?></p>
  <?php endif; ?>
</main>

<div class="fjord-filter-drawer" data-filter-drawer aria-hidden="true">
  <div class="fjord-filter-drawer__overlay" data-filter-drawer-close></div>
  <aside class="fjord-filter-drawer__panel" role="dialog" aria-modal="true" aria-label="Filters">
    <div class="fjord-filter-drawer__header">
      <span class="fjord-filter-drawer__title"><?php esc_html_e('Filtros', 'fjord-clone'); ?></span>
      <button class="fjord-filter-drawer__close" type="button" data-filter-drawer-close aria-label="Cerrar">×</button>
    </div>

    <div class="fjord-filter-drawer__content">
      <section class="fjord-filter-drawer__section">
        <h3 class="fjord-filter-drawer__section-title"><?php esc_html_e('Categorías', 'fjord-clone'); ?></h3>
        <div class="fjord-filter-drawer__list">
          <?php
          if (!is_wp_error($categories) && !empty($categories)) {
            foreach ($categories as $category) {
              $link = get_term_link($category);
              if (is_wp_error($link)) {
                continue;
              }
              $active = is_tax('product_cat', $category->term_id);
              printf(
                '<a class="fjord-filter-drawer__link%s" href="%s">%s</a>',
                $active ? ' is-active' : '',
                esc_url($link),
                esc_html($category->name)
              );
            }
          }
          ?>
        </div>
      </section>

      <section class="fjord-filter-drawer__section">
        <h3 class="fjord-filter-drawer__section-title"><?php esc_html_e('Precio', 'fjord-clone'); ?></h3>
        <form class="fjord-filter-drawer__price" method="get" action="<?php echo esc_url($shop_base); ?>">
          <?php
          foreach ($filter_args as $key => $value) {
            if (in_array($key, ['min_price', 'max_price'], true)) {
              continue;
            }
            if (is_array($value)) {
              foreach ($value as $item) {
                printf('<input type="hidden" name="%s[]" value="%s">', esc_attr($key), esc_attr($item));
              }
            } else {
              printf('<input type="hidden" name="%s" value="%s">', esc_attr($key), esc_attr($value));
            }
          }
          ?>
          <div class="fjord-filter-drawer__price-range" data-price-range data-currency="<?php echo esc_attr($currency_symbol); ?>" data-decimals="<?php echo esc_attr($price_decimals); ?>">
            <div class="fjord-filter-drawer__price-track">
              <input
                type="range"
                name="min_price_range"
                min="0"
                max="<?php echo esc_attr($max_price); ?>"
                step="1"
                value="<?php echo esc_attr($min_price_value); ?>"
                aria-label="<?php esc_attr_e('Precio mínimo', 'fjord-clone'); ?>"
              >
              <input
                type="range"
                name="max_price_range"
                min="0"
                max="<?php echo esc_attr($max_price); ?>"
                step="1"
                value="<?php echo esc_attr($max_price_value ?: $max_price); ?>"
                aria-label="<?php esc_attr_e('Precio máximo', 'fjord-clone'); ?>"
              >
            </div>
            <div class="fjord-filter-drawer__price-value" data-price-output>
              <?php
              $display_min = number_format_i18n($min_price_value, $price_decimals);
              $display_max = number_format_i18n($max_price_value ?: $max_price, $price_decimals);
              echo esc_html(sprintf('%s %s — %s %s', $currency_symbol, $display_min, $currency_symbol, $display_max));
              ?>
            </div>
          </div>
          <div class="fjord-filter-drawer__price-row">
            <input type="number" name="min_price" placeholder="Min" min="0" value="<?php echo esc_attr($_GET['min_price'] ?? ''); ?>">
            <input type="number" name="max_price" placeholder="Max" min="0" value="<?php echo esc_attr($_GET['max_price'] ?? ''); ?>">
          </div>
          <button type="submit" class="fjord-filter-drawer__apply"><?php esc_html_e('Aplicar', 'fjord-clone'); ?></button>
        </form>
      </section>

      <?php
      if (!empty($attribute_taxonomies)) {
        foreach ($attribute_taxonomies as $attribute) {
          $taxonomy = wc_attribute_taxonomy_name($attribute->attribute_name);
          if (!taxonomy_exists($taxonomy)) {
            continue;
          }
          $terms = get_terms([
            'taxonomy' => $taxonomy,
            'hide_empty' => false,
          ]);
          if (is_wp_error($terms) || empty($terms)) {
            continue;
          }
          $param = 'filter_' . $attribute->attribute_name;
          $active_terms = isset($_GET[$param]) ? array_map('sanitize_title', explode(',', wp_unslash($_GET[$param]))) : [];
          ?>
          <section class="fjord-filter-drawer__section">
            <h3 class="fjord-filter-drawer__section-title"><?php echo esc_html($attribute->attribute_label ?: $attribute->attribute_name); ?></h3>
            <div class="fjord-filter-drawer__list">
              <?php
              foreach ($terms as $term) {
                $is_active = in_array($term->slug, $active_terms, true);
                $url = add_query_arg(array_merge($filter_args, [$param => $term->slug]), $shop_base);
                printf(
                  '<a class="fjord-filter-drawer__link%s" href="%s">%s</a>',
                  $is_active ? ' is-active' : '',
                  esc_url($url),
                  esc_html($term->name)
                );
              }
              ?>
            </div>
          </section>
          <?php
        }
      }
      ?>

      <?php if ($is_filtered) : ?>
        <a class="fjord-filter-drawer__clear" href="<?php echo esc_url($shop_base); ?>">
          <?php esc_html_e('Limpiar filtros', 'fjord-clone'); ?>
        </a>
      <?php endif; ?>
    </div>
  </aside>
</div>

<?php get_footer(); ?>
