jQuery(document).ready(function () {
  const isMobile = () => window.innerWidth <= 480;
  const $overlay = jQuery('.testimonial-overlay');

  jQuery('.testimonial').each(function (index) {
    const $this = jQuery(this);
    const contentId = 'testimonial-' + index;

    $this.attr({
      'aria-expanded': 'false',
      'aria-controls': contentId,
    });

    $this.find('.testim_content').attr('id', contentId);
  });

  function expandTestimonial($el) {
    jQuery('.testimonial')
      .not($el)
      .removeClass('expanded addContent')
      .attr('aria-expanded', 'false');

    $el.addClass('expanded').attr('aria-expanded', 'true');

    if (isMobile()) {
      $overlay.addClass('active');
    }

    setTimeout(() => {
      $el.addClass('addContent');
    }, 2000);
  }

  function collapseTestimonial($el) {
    $el.removeClass('expanded addContent').attr('aria-expanded', 'false');

    if (isMobile()) {
      $overlay.removeClass('active');
    }
  }

  if (!isMobile()) {
    const $first = jQuery('.testimonial').first();
    $first.addClass('expanded addContent').attr('aria-expanded', 'true');
  }

  jQuery('.testimonial').on('click', function (e) {
    if (jQuery(e.target).hasClass('close-testimonial')) return;

    const $this = jQuery(this);
    if (!$this.hasClass('expanded')) {
      expandTestimonial($this);
    }
  });

  jQuery('.close-testimonial').on('click', function (e) {
    e.stopPropagation();
    const $parent = jQuery(this).closest('.testimonial');
    collapseTestimonial($parent);
  });

  jQuery('.testimonial').on('keydown', function (e) {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      expandTestimonial(jQuery(this));
    }
  });
});
