(function () {
  'use strict';
  const reviews = window.REVIEWS || [];
  const grid = document.getElementById('reviewGrid');
  const summary = document.getElementById('reviewSummary');
  const modal = document.getElementById('reviewModal');
  if (!grid) return;

  function starsHTML(rating) {
    let html = '<span class="stars" aria-label="' + rating + ' out of 5">';
    for (let i = 1; i <= 5; i++) {
      html += i <= rating
        ? '<i class="ic star-on" data-ic="star"></i>'
        : '<i class="ic star-off" data-ic="star"></i>';
    }
    return html + '</span>';
  }

  function paintIcons(scope) {
    const map = {
      star: '<svg viewBox="0 0 24 24" width="17" height="17" fill="currentColor"><path d="m12 2 3 6.6 7 .8-5.2 4.9 1.4 7L12 17.8 5.8 21.3l1.4-7L2 9.4l7-.8L12 2z"/></svg>',
    };
    (scope || document).querySelectorAll('.ic[data-ic]').forEach(function (el) {
      if (map[el.getAttribute('data-ic')]) el.innerHTML = map[el.getAttribute('data-ic')];
    });
  }

  function render() {
    if (!reviews.length) {
      grid.innerHTML = '<div class="empty" style="padding:40px 20px;"><div class="ico"><i class="ic" data-ic="heart"></i></div><h3>No reviews yet</h3><p>Be the first to tell the world about your TOUS CINO experience.</p></div>';
      return;
    }
    let html = '';
    reviews.forEach(function (r) {
      const initials = (r.name || '?').split(' ').map(function (w) { return w[0]; }).slice(0, 2).join('').toUpperCase();
      html += `<article class="review-card">
        <div class="review-top">
          <div class="review-avatar">${initials}</div>
          <div>
            <div class="review-name">${r.name}${r.city ? ' <span class="review-city">· ' + r.city + '</span>' : ''}</div>
            ${starsHTML(r.rating)}
          </div>
        </div>
        <h4 class="review-title">${r.title || 'Review'}</h4>
        <p class="review-body">${r.body}</p>
        <div class="review-date">Verified TOUS CINO customer</div>
      </article>`;
    });
    grid.innerHTML = html;
    paintIcons(grid);

    const avg = reviews.reduce(function (s, r) { return s + r.rating; }, 0) / reviews.length;
    const el = document.getElementById('rsAvg');
    const stars = document.getElementById('rsStars');
    const count = document.getElementById('rsCount');
    if (summary) summary.hidden = false;
    if (el) el.textContent = avg.toFixed(1);
    if (stars) stars.innerHTML = starsHTML(Math.round(avg));
    if (count) count.textContent = 'based on ' + reviews.length + ' review' + (reviews.length === 1 ? '' : 's');
    paintIcons(stars);
  }

  /* modal */
  function openModal() { if (modal) modal.hidden = false; document.body.style.overflow = 'hidden'; }
  function closeModal() { if (modal) modal.hidden = true; document.body.style.overflow = ''; }

  const openBtn = document.getElementById('openReviewBtn');
  if (openBtn) openBtn.addEventListener('click', openModal);
  const closeBtn = document.getElementById('reviewModalClose');
  if (closeBtn) closeBtn.addEventListener('click', closeModal);
  if (modal) modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });

  /* open directly when arriving via a review-request link (?leave-review=1) */
  if (/(^|[?&])leave-review=1($|&)/.test(location.search)) {
    setTimeout(openModal, 900);
  }

  /* auto-open after the buyer's order has been fulfilled */
  (function () {
    let stored = null;
    try { stored = localStorage.getItem('tc_review_order'); } catch (e) {}
    if (!stored) return;
    fetch('/api/order-status?number=' + encodeURIComponent(stored))
      .then(function (r) { return r.json(); })
      .then(function (d) {
        if (d.fulfilled) setTimeout(openModal, 1200);
      })
      .catch(function () {});
  })();

  /* star picker */
  let chosen = 0;
  const picker = document.getElementById('starPicker');
  if (picker) {
    picker.querySelectorAll('.sp-star').forEach(function (b) {
      b.addEventListener('click', function () {
        chosen = Number(b.dataset.v);
        picker.querySelectorAll('.sp-star').forEach(function (x) {
          x.classList.toggle('on', Number(x.dataset.v) <= chosen);
        });
      });
    });
  }

  /* submit */
  const form = document.getElementById('reviewForm');
  if (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      const payload = {
        name: document.getElementById('rvName').value,
        city: document.getElementById('rvCity').value,
        title: document.getElementById('rvTitle').value,
        body: document.getElementById('rvBody').value,
        rating: chosen || 5,
      };
      const btn = form.querySelector('button[type="submit"]');
      btn.disabled = true;
      btn.textContent = 'Submitting...';
      fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
        .then(function (r) { return r.json(); })
        .then(function (d) {
          if (d.ok) {
            TC.toast('Thank you! Your review is awaiting approval.');
            try { localStorage.removeItem('tc_review_order'); } catch (e) {}
            form.reset();
            chosen = 0;
            if (picker) picker.querySelectorAll('.sp-star').forEach(function (x) { x.classList.remove('on'); });
            closeModal();
          } else {
            TC.toast(d.error || 'Could not submit review', 'error');
          }
        })
        .catch(function () { TC.toast('Network error — try again', 'error'); })
        .finally(function () { btn.disabled = false; btn.innerHTML = 'Submit review'; });
    });
  }

  render();
})();
