<?php

/**
 * Comments template – clean, accessible, threaded, video-friendly
 * Place in your theme root.
 */

if (post_password_required()) {
  return;
}

// Tạo nonce cho hành động like/dislike (để bạn dùng AJAX về sau)
$react_nonce = wp_create_nonce('comment-react-nonce');
?>

<section id="comments" class="comments" aria-labelledby="comments-title">
  <header class="comments__header">
    <?php
    $count = get_comments_number();
    ?>
    <h2 id="comments-title" class="comments__title">
      <?php
      printf(
        /* translators: %s: number of comments */
        esc_html__('Comments (%s)', 'easy3x'),
        number_format_i18n($count)
      );
      ?>
    </h2>
  </header>

  <?php if (comments_open()) : ?>
    <div id="respond" class="comment-respond">
      <?php
      // Loại bỏ field URL (nếu theme/plugin khác thêm vào)
      add_filter('comment_form_default_fields', function ($fields) {
        unset($fields['url']);
        return $fields;
      });

      $req         = get_option('require_name_email');
      $aria_req    = $req ? ' aria-required="true" required' : '';
      $author_val  = esc_attr(wp_get_current_commenter()['comment_author'] ?? '');
      $email_val   = esc_attr(wp_get_current_commenter()['comment_author_email'] ?? '');

      comment_form([
        'title_reply'          => __('', 'easy3x'),
        'title_reply_before'   => '<h3 id="reply-title" class="comments__form-title">',
        'title_reply_after'    => '</h3>',
        'comment_notes_before' => '',
        'comment_notes_after'  => '',
        'label_submit'         => __('Submit', 'easy3x'),
        'class_form'           => 'comment-form is-clean',
        'class_submit'         => 'btn btn--primary',
        'id_form'              => 'commentform',
        'id_submit'            => 'submit',
        'submit_field'         => '<p class="form-submit">%1$s %2$s</p>',
        'fields'               => [
          'author' =>
          '<p class="comment-form-author">' .
            '<label for="author" class="sr-only">' . __('Name', 'easy3x') . '</label>' .
            '<input id="author" name="author" type="text" value="' . $author_val . '" placeholder="' . esc_attr__('Name*', 'easy3x') . '" ' . $aria_req . ' />' .
            '</p>',

          'email'  =>
          '<p class="comment-form-email">' .
            '<label for="email" class="sr-only">' . __('Email', 'easy3x') . '</label>' .
            '<input id="email" name="email" type="email" value="' . $email_val . '" placeholder="' . esc_attr__('Email*', 'easy3x') . '" ' . $aria_req . ' />' .
            '</p>',
        ],
        'comment_field'        =>
        '<p class="comment-form-comment">' .
          '<label for="comment" class="sr-only">' . __('Content', 'easy3x') . '</label>' .
          '<textarea id="comment" name="comment" cols="45" rows="5" placeholder="' . esc_attr__('Write your comment…', 'easy3x') . '" aria-required="true" required></textarea>' .
          '</p>',
        'logged_in_as'         => '',
      ]);
      ?>
    </div>
  <?php elseif (get_comments_number()) : ?>
    <p class="no-comments"><?php _e('Đã đóng bình luận.', 'easy3x'); ?></p>
  <?php endif; ?>


  <?php if (have_comments()) : ?>
    <ol class="comment-list" role="list">
      <?php
      // Callback render mỗi comment
      wp_list_comments([
        'style'        => 'ol',
        'short_ping'   => true,
        'avatar_size'  => 48,
        'max_depth'    => get_option('thread_comments_depth'),
        'callback'     => function ($comment, $args, $depth) use ($react_nonce) {
          $is_pending = '0' === $comment->comment_approved;
          $cid        = $comment->comment_ID;
          $author     = get_comment_author_link($comment);
          $permalink  = esc_url(get_comment_link($comment));
          $datetime   = esc_attr(get_comment_time('c'));
          $comment_time = get_comment_time('U', true, $comment); // timestamp của comment
          $current_time = current_time('timestamp');
          $time_diff    = human_time_diff($comment_time, $current_time);
          $date_text    = sprintf(__('%s trước', 'easy3x'), $time_diff);
          $classes    = join(' ', get_comment_class('comment', $comment));
          $like_count = (int) get_comment_meta($cid, '_like', true);
          $dis_count  = (int) get_comment_meta($cid, '_dislike', true);
      ?>
        <li id="comment-<?php echo (int)$cid; ?>" class="<?php echo esc_attr($classes); ?>" itemprop="comment">
          <article id="div-comment-<?php echo (int)$cid; ?>" class="comment__body">
            <div class="comment__avatar">
              <?php echo get_avatar($comment, $args['avatar_size'], '', '', ['class' => 'avatar']); ?>
            </div>

            <div class="comment__content">
              <div class="comment__meta">
                <span class="comment__author"><?php echo wp_kses_post($author); ?></span>
                <time class="comment__time" datetime="<?php echo $datetime; ?>">
                  <a href="<?php echo $permalink; ?>"><?php echo $date_text; ?></a>
                </time>
                <?php edit_comment_link(__('Edit', 'easy3x'), '<span class="comment__edit">', '</span>'); ?>
              </div>

              <div class="comment__text">
                <?php if ($is_pending) : ?>
                  <em class="comment-awaiting"><?php _e('Bình luận đang chờ duyệt.', 'easy3x'); ?></em>
                <?php endif; ?>
                <?php comment_text($comment); ?>
              </div>

              <div class="comment__toolbar" role="group" aria-label="<?php esc_attr_e('Tương tác bình luận', 'easy3x'); ?>">
                <button class="cbtn cbtn--react cbtn--like"
                  type="button"
                  data-cid="<?php echo (int)$cid; ?>"
                  data-action="like"
                  data-nonce="<?php echo esc_attr($react_nonce); ?>"
                  aria-pressed="false">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-thumbs-up" aria-hidden="true">
                    <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"></path>
                  </svg>
                  <span class="cbtn__count" aria-live="polite"><?php echo (int)$like_count; ?></span>
                </button>

                <button class="cbtn cbtn--react cbtn--dislike"
                  type="button"
                  data-cid="<?php echo (int)$cid; ?>"
                  data-action="dislike"
                  data-nonce="<?php echo esc_attr($react_nonce); ?>"
                  aria-pressed="false">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-thumbs-down" aria-hidden="true">
                    <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"></path>
                  </svg>
                  <span class="cbtn__count" aria-live="polite"><?php echo (int)$dis_count; ?></span>
                </button>

                <?php
                comment_reply_link(array_merge($args, [
                  'reply_text' => __('Trả lời', 'easy3x'),
                  'add_below'  => 'div-comment',
                  'depth'      => $depth,
                  'max_depth'  => $args['max_depth'],
                  'before'     => '<span class="cbtn cbtn--reply">',
                  'after'      => '</span>',
                ]), $comment, $comment->comment_post_ID);
                ?>
              </div>
            </div>
          </article>
        <?php
        },
        'end-callback' => function () {
          echo "</li>";
        },
      ]);
        ?>
    </ol>

    <?php if (get_comment_pages_count() > 1 && get_option('page_comments')) : ?>
      <nav class="comments__pagination" aria-label="<?php esc_attr_e('Phân trang bình luận', 'easy3x'); ?>">
        <?php
        paginate_comments_links([
          'prev_text' => __('← Trước', 'easy3x'),
          'next_text' => __('Tiếp →', 'easy3x'),
          'type'      => 'list',
        ]);
        ?>
      </nav>
    <?php endif; ?>

  <?php endif; // have_comments
  ?>

</section>

<?php
// JS nho nhỏ: xử lý giao diện like/dislike (tăng số, toggle aria-pressed)
// Bạn có thể thay bằng AJAX thực tế (admin-ajax.php) để lưu meta _like/_dislike.
?>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const reacts = document.querySelectorAll('.cbtn--react');
    reacts.forEach(btn => {
      btn.addEventListener('click', function() {
        const pressed = this.getAttribute('aria-pressed') === 'true';
        this.setAttribute('aria-pressed', (!pressed).toString());
        const cnt = this.querySelector('.cbtn__count');
        if (cnt) {
          let v = parseInt(cnt.textContent || '0', 10);
          cnt.textContent = (pressed ? Math.max(0, v - 1) : v + 1);
        }
        // TODO: gửi AJAX với dataset (data-cid, data-action, data-nonce)
      });
    });
  });
</script>