<?php
get_header();

if ( function_exists( 'wp_body_open' ) ) {
    wp_body_open();
}

wp_enqueue_style(
    'caffito-archive',
    get_template_directory_uri() . '/assets/css/archive.css',
    [],
    null
);
?>

<section class="archive-page" aria-labelledby="archive-page-title">
 
    <?php if ( have_posts() ) : ?>
        <div class="archive-grid">
            <?php
            while ( have_posts() ) :
                the_post();
                $post_categories = get_the_terms( get_the_ID(), 'category' );
                $category_slugs  = [];
                if ( ! empty( $post_categories ) && ! is_wp_error( $post_categories ) ) {
                    foreach ( $post_categories as $term ) {
                        $category_slugs[] = sanitize_html_class( $term->slug );
                    }
                }
                $category_data_attr = $category_slugs ? implode( ' ', $category_slugs ) : 'uncategorized';
                $published_timestamp = get_post_time( 'U', true );
                $datetime_attr       = get_post_time( DATE_W3C, true );
                $display_date        = function_exists( 'smart_date' )
                    ? smart_date( 'j F Y', $published_timestamp )
                    : get_the_date();
                ?>
                <a
                    <?php post_class( 'archive-card' ); ?>
                    href="<?php the_permalink(); ?>"
                    aria-labelledby="post-<?php the_ID(); ?>-title"
                    data-filter-cats="<?php echo esc_attr( $category_data_attr ); ?>"
                >
                    <?php if ( has_post_thumbnail() ) : ?>
                        <span class="archive-card__media">
                            <?php the_post_thumbnail( 'medium_large', [ 'class' => 'archive-card__image', 'loading' => 'lazy' ] ); ?>
                        </span>
                    <?php else : ?>
                        <span class="archive-card__media archive-card__media--default">
                            <img
                                src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/coffee-img/coffee-img-1.webp' ); ?>"
                                alt="<?php esc_attr_e( 'تصویر پیش‌فرض مقاله', 'caffito' ); ?>"
                                class="archive-card__image"
                                loading="lazy"
                            >
                        </span>
                    <?php endif; ?>

                    <span class="archive-card__body">
                        <header class="archive-card__header">
                            <h2 id="post-<?php the_ID(); ?>-title" class="archive-card__title">
                                <?php the_title(); ?>
                            </h2>
                        </header>

                        <span class="archive-card__excerpt">
                            <?php the_excerpt(); ?>
                        </span>

                    </span>
                </a>
            <?php endwhile; ?>
        </div>

        <nav class="archive-pagination" aria-label="<?php esc_attr_e( 'صفحات مقالات', 'caffito' ); ?>">
            <?php
            the_posts_pagination(
                [
                    'mid_size'           => 2,
                    'prev_text'          => __( 'قبلی', 'caffito' ),
                    'next_text'          => __( 'بعدی', 'caffito' ),
                    'class'              => 'archive-pagination__links',
                    'screen_reader_text' => __( 'صفحه‌بندی', 'caffito' ),
                ]
            );
            ?>
        </nav>
    <?php else : ?>
        <div class="archive-empty">
            <p class="archive-empty__message"><?php esc_html_e( 'هنوز هیچ مقاله‌ای منتشر نشده است.', 'caffito' ); ?></p>
            <a class="archive-empty__link" href="<?php echo esc_url( home_url( '/' ) ); ?>">
                <?php esc_html_e( 'بازگشت به صفحه اصلی', 'caffito' ); ?>
            </a>
        </div>
    <?php endif; ?>
</section>

<?php
wp_register_script( 'caffito-archive-filter', false, [], null, true );
wp_enqueue_script( 'caffito-archive-filter' );
$filter_script = <<<JS
document.addEventListener('DOMContentLoaded', function () {
  var filterBar = document.querySelector('.archive-filter');
  if (!filterBar) return;

  var buttons = filterBar.querySelectorAll('.archive-filter__button');
  var cards = document.querySelectorAll('.archive-card');

  function setActive(button) {
    buttons.forEach(function (btn) {
      btn.classList.toggle('is-active', btn === button);
    });
  }

  function applyFilter(slug) {
    cards.forEach(function (card) {
      var catString = card.getAttribute('data-filter-cats') || '';
      var categories = catString.split(/\s+/).filter(Boolean);
      var match = slug === 'all' || categories.includes(slug);
      card.style.display = match ? '' : 'none';
    });
  }

  filterBar.addEventListener('click', function (event) {
    var target = event.target.closest('.archive-filter__button');
    if (!target) return;
    var slug = target.getAttribute('data-filter');
    if (!slug) return;
    event.preventDefault();
    setActive(target);
    applyFilter(slug);
  });
});
JS;
wp_add_inline_script( 'caffito-archive-filter', $filter_script );
?>

<?php get_footer(); ?>
