<section class="category-grid sections">
  <h2 class="section-title">Categories</h2>

  <?php
  // Lấy 15 category phổ biến nhất
  $categories = get_categories([
    'orderby'    => 'count',
    'order'      => 'DESC',
    'number'     => 10,
    'hide_empty' => true,
  ]);
  ?>

  <div class="grid" id="categoryGrid">
    <?php foreach ($categories as $category): ?>
      <?php
      // Lấy post mới nhất trong category để lấy thumbnail
      $latest_post = get_posts([
        'category'       => $category->term_id,
        'posts_per_page' => 1,
        'post_status'    => 'publish',
        'no_found_rows'  => true,
        'fields'         => 'ids', // Chỉ lấy ID cho nhanh
      ]);

      $thumbnail_url = (!empty($latest_post) && has_post_thumbnail($latest_post[0]))
        ? get_the_post_thumbnail_url($latest_post[0], 'thumb-16x9')
        : 'https://via.placeholder.com/300x400?text=No+Image';

      $term_link = get_category_link($category);
      ?>
      <article class="category-card">
        <a href="<?php echo esc_url($term_link); ?>" class="card-link" 
           title="<?php echo esc_attr($category->name); ?>" rel="category">
          <div class="card-thumb">
            <img src="<?php echo esc_url($thumbnail_url); ?>" 
                 alt="<?php echo esc_attr($category->name); ?>" loading="lazy">
            <div class="card-content">
              <h3 class="card-title"><?php echo esc_html($category->name); ?></h3>
              <p class="card-count"><?php echo intval($category->count); ?> videos</p>
            </div>
          </div>
        </a>
      </article>
    <?php endforeach; ?>
  </div>
</section>
