// Google Reviews carousel — data managed via admin panel, fetched live
// Add/edit/hide reviews in the admin Reviews tab; changes appear here automatically.

function StarRow({ rating }) {
  return (
    <div style={{ display: 'flex', gap: 2 }}>
      {[1,2,3,4,5].map(n => (
        <i key={n} data-lucide="star" style={{ width: 16, height: 16, color: n <= rating ? '#F5B940' : '#E8D5C4', fill: n <= rating ? '#F5B940' : '#E8D5C4' }}></i>
      ))}
    </div>
  );
}

function ReviewCard({ review }) {
  return (
    <div style={{ background: '#FFFBF5', border: '1px solid #F0E0CE', borderRadius: 18, padding: '24px 22px', display: 'flex', flexDirection: 'column', gap: 14, minWidth: 320, maxWidth: 320, flexShrink: 0, scrollSnapAlign: 'start', boxSizing: 'border-box', minHeight: 220 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <StarRow rating={review.rating} />
        <i data-lucide="quote" style={{ width: 22, height: 22, color: '#F0E0CE' }}></i>
      </div>
      <p style={{ fontSize: 14.5, color: '#5C4A37', lineHeight: 1.6, margin: 0, flex: 1 }}>{review.body}</p>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, paddingTop: 6, borderTop: '1px solid #F4E8DA' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: '50%', flexShrink: 0, background: '#F0E2D0', color: '#8B5A2B', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'Fraunces', serif", fontWeight: 600, fontSize: 15 }}>
            {review.reviewer_name.charAt(0)}
          </div>
          <div style={{ fontFamily: "'Fraunces', serif", fontWeight: 600, fontSize: 15, color: '#3D2817', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {review.reviewer_name}
          </div>
        </div>
        <span style={{ fontSize: 12, color: '#A89580', whiteSpace: 'nowrap', flexShrink: 0 }}>{review.review_date}</span>
      </div>
    </div>
  );
}

function ReviewsCarousel() {
  const [reviews, setReviews] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const scrollerRef = React.useRef(null);
  const pausedRef   = React.useRef(false);

  React.useEffect(() => {
    fetch('/api/products?resource=reviews')
      .then(r => r.json())
      .then(d => setReviews(d.reviews || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  React.useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  // Auto-scroll
  React.useEffect(() => {
    const el = scrollerRef.current;
    if (!el || reviews.length === 0) return;
    let raf;
    const step = () => {
      if (!pausedRef.current && el) {
        if (el.scrollLeft + el.clientWidth >= el.scrollWidth - 1) el.scrollLeft = 0;
        else el.scrollLeft += 0.5;
      }
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [reviews]);

  const scrollByCards = dir => {
    scrollerRef.current?.scrollBy({ left: dir * 340, behavior: 'smooth' });
  };
  const pause  = () => { pausedRef.current = true; };
  const resume = () => { pausedRef.current = false; };

  // Don't render section at all if no reviews yet
  if (!loading && reviews.length === 0) return null;

  return (
    <section style={{ padding: '64px 24px', background: '#F0E2D0' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12, marginBottom: 28 }}>
          <div>
            <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 'clamp(24px, 5vw, 40px)', fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 6px', color: '#3D2817' }}>Kind Words.</h2>
            <div style={{ fontFamily: "'Fraunces', serif", fontStyle: 'italic', color: '#8B6F4E', fontSize: 'clamp(15px, 2vw, 17px)' }}>What our customers say</div>
          </div>
          {!loading && reviews.length > 1 && (
            <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
              <button onClick={() => scrollByCards(-1)} aria-label="Previous" style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #E8D5C4', background: '#FFFBF5', color: '#8B6F4E', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i data-lucide="chevron-left" style={{ width: 20, height: 20 }}></i>
              </button>
              <button onClick={() => scrollByCards(1)} aria-label="Next" style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #E8D5C4', background: '#FFFBF5', color: '#8B6F4E', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i data-lucide="chevron-right" style={{ width: 20, height: 20 }}></i>
              </button>
            </div>
          )}
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: '32px 0', color: '#8B6F4E', fontFamily: "'Fraunces', serif", fontStyle: 'italic' }}>Loading reviews…</div>
        ) : (
          <div ref={scrollerRef} onMouseEnter={pause} onMouseLeave={resume} onTouchStart={pause} onTouchEnd={resume}
            style={{ display: 'flex', gap: 16, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 8, scrollbarWidth: 'none', msOverflowStyle: 'none' }}
            className="reviews-scroller">
            {reviews.map(r => <ReviewCard key={r.id} review={r} />)}
          </div>
        )}


      </div>
      <style>{`.reviews-scroller::-webkit-scrollbar{display:none}`}</style>
    </section>
  );
}

window.ReviewCard      = ReviewCard;
window.ReviewsCarousel = ReviewsCarousel;
