// ============================================================
// Đánh giá khách thật từ Shopee (dữ liệu: src/reviews.js do tools/danh-gia.ps1 sinh).
//   JmCustomerPhotos  — dải "Ảnh thật từ khách hàng · Shopee" dưới bộ ảnh chính (tối đa 8)
//   JmProductReviews  — khối "Khách hàng nói gì" trên trang sản phẩm (3–5 đánh giá)
//   JmReviewLightbox  — ảnh lớn kèm lời đánh giá
// Không có đánh giá phù hợp thì ẩn hẳn, không viết đánh giá mẫu.
// ============================================================

function JmStars() {
  return <span className="jm-rv__stars" aria-label="5 sao">★★★★★</span>;
}

function JmReviewLightbox({ item, lang, onClose }) {
  React.useEffect(() => {
    if (!item) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [item]);
  React.useEffect(() => { if (item && window.lucide) lucide.createIcons(); });
  if (!item) return null;
  const r = item.review;
  return (
    <div className="jm-rv-lightbox" onClick={onClose} role="dialog" aria-modal="true">
      <figure onClick={(e) => e.stopPropagation()}>
        <button className="jm-rv-lightbox__close" onClick={onClose} aria-label={lang === 'vi' ? 'Đóng' : 'Close'}><i data-lucide="x" className="jm-icon"></i></button>
        <img src={item.src} alt={lang === 'vi' ? 'Ảnh khách hàng chụp' : 'Customer photo'}/>
        <figcaption>
          <JmStars/>
          <p>{r.text}</p>
          <span className="jm-small">{r.name}{r.variant ? ` · ${lang === 'vi' ? 'Phân loại' : 'Variant'}: ${r.variant}` : ''} · {lang === 'vi' ? 'Đánh giá từ Shopee' : 'Review from Shopee'}</span>
        </figcaption>
      </figure>
    </div>
  );
}

// Ảnh khách, ưu tiên ảnh của khách mua đúng màu đang chọn
JM.customerPhotos = (code, colorKey, max = 8) => {
  const list = JM.productReviews[code] || [];
  const same = (r) => !colorKey || !r.color || r.color === colorKey || (colorKey === 'platinum' && r.color === 'silver');
  const ordered = [...list.filter(same), ...list.filter(r => !same(r))];
  const out = [];
  ordered.forEach(r => (r.imgs || []).forEach(src => out.push({ src, review: r })));
  return out.slice(0, max);
};

function JmCustomerPhotos({ code, colorKey, lang, onOpen }) {
  const photos = JM.customerPhotos(code, colorKey);
  if (!photos.length) return null;
  return (
    <div className="jm-rv-strip">
      <div className="jm-rv-strip__label">{lang === 'vi' ? 'Ảnh thật từ khách hàng · Shopee' : 'Real customer photos · Shopee'}</div>
      <div className="jm-rv-strip__row">
        {photos.map((ph, i) => (
          <button key={ph.src} className="jm-rv-strip__item" onClick={() => onOpen(ph)} aria-label={`${lang === 'vi' ? 'Ảnh khách' : 'Customer photo'} ${i + 1}`}>
            <img src={ph.src} alt="" loading="lazy"/>
          </button>
        ))}
      </div>
    </div>
  );
}

function JmProductReviews({ code, lang, onOpen }) {
  const list = (JM.productReviews[code] || []).filter(r => r.card);
  if (list.length === 0) return null;
  return (
    <section className="jm-rv" aria-labelledby="jm-rv-title">
      <div className="jm-label" style={{ color: 'var(--jm-cam-dat)' }}>{lang === 'vi' ? 'Đánh giá từ Shopee' : 'Reviews from Shopee'}</div>
      <h3 id="jm-rv-title" className="jm-h2" style={{ margin: '8px 0 24px' }}>{lang === 'vi' ? 'Khách hàng nói gì' : 'What customers say'}</h3>
      <div className="jm-rv__grid">
        {list.map(r => (
          <article className="jm-rv__card" key={r.id}>
            <JmStars/>
            <p className="jm-rv__text">{r.text}</p>
            {r.imgs && r.imgs.length > 0 && (
              <div className="jm-rv__imgs">
                {r.imgs.map(src => (
                  <button key={src} onClick={() => onOpen({ src, review: r })} aria-label={lang === 'vi' ? 'Phóng to ảnh' : 'Enlarge photo'}>
                    <img src={src} alt="" loading="lazy"/>
                  </button>
                ))}
              </div>
            )}
            <div className="jm-rv__meta">
              <span>{r.name}</span>
              {r.variant && <span>{lang === 'vi' ? 'Phân loại' : 'Variant'}: {r.variant}</span>}
              <span className="jm-rv__src">{lang === 'vi' ? 'Đánh giá từ Shopee' : 'Review from Shopee'}</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

window.JmReviewLightbox = JmReviewLightbox;
window.JmCustomerPhotos = JmCustomerPhotos;
window.JmProductReviews = JmProductReviews;
window.JmStars = JmStars;
