document.querySelectorAll('.rating').forEach(container => {
  const photoId = container.dataset.id;
  container.querySelectorAll('.star').forEach(star => {
    star.addEventListener('click', () => {
      const rating = star.dataset.rating;
      fetch('rate.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `photo_id=${photoId}&rating=${rating}`
      })
      .then(res => res.json())
      .then(data => {
        if (data.avg) {
          container.querySelectorAll('.star').forEach(s => {
            s.classList.toggle('filled', s.dataset.rating <= Math.round(data.avg));
          });
          const count = container.querySelector('.count');
          if (count) {
            count.textContent = `(${data.avg} ★, ${data.cnt} Bewertungen)`;
          }
        }
      });
    });
  });
});