'use client';
import { useState, useEffect } from 'react';
import styles from './AboutTestimonial.module.css';
import { formatReviewsForAbout } from '@/lib/reviewUtils';

export default function AboutTestimonial() {
  const [active, setActive] = useState(0);
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadReviews() {
      try {
        const res = await fetch('/api/reviews');
        const data = await res.json().catch(() => ({}));

        if (!res.ok) {
          const errorMessage = data?.error || `${res.status} ${res.statusText}`;
          console.warn('About reviews API returned non-ok response:', errorMessage);
        }

        if (data.error) {
          console.warn('About reviews API returned an error payload:', data.error);
        }

        const formatted = formatReviewsForAbout(Array.isArray(data.reviews) ? data.reviews : []);
        setReviews(formatted);
      } catch (error) {
        console.error('Failed to load reviews:', error);
        setReviews([]);
      } finally {
        setLoading(false);
      }
    }

    loadReviews();
  }, []);

  const testimonials = reviews;

  useEffect(() => {
    if (!testimonials.length) return;
    
    const timer = setInterval(() => {
      setActive((prev) => (prev + 1) % testimonials.length);
    }, 4000);
    return () => clearInterval(timer);
  }, [testimonials.length]);

  const t = testimonials.length ? testimonials[active % testimonials.length] : null;

  return (
    <section className={styles.section}>
      <div className={styles.container}>
        <div className={styles.header}>
          <span className={styles.eyebrow}>
            <span className={styles.eyebrowIcon}>💬</span> What Guests Say
          </span>
          <h2 className={styles.title}>
            Stories from Our <em>Table</em>
          </h2>
        </div>

        <div className={styles.testimonialArea}>
          {loading && <p className={styles.loadingText}>Loading Google reviews...</p>}
          {!loading && !testimonials.length && (
            <p className={styles.loadingText}>No Google reviews available right now.</p>
          )}
          {!loading && t && (
            <>
              <div className={styles.quoteBox} key={active}>
                <div className={styles.quoteIcon}>&ldquo;</div>
                <blockquote className={styles.quote}>{t.quote}</blockquote>
                <div className={styles.author}>
                  <div className={styles.authorAvatar}>{t.name.charAt(0)}</div>
                  <div className={styles.authorInfo}>
                    <strong>{t.name}</strong>
                    <span>{t.role}</span>
                  </div>
                  {/* <div className={styles.stars}>{'★'.repeat(t.rating)}</div> */}
                </div>
              </div>

              <div className={styles.dots}>
                {testimonials.map((_, i) => (
                  <button
                    key={i}
                    className={`${styles.dot} ${i === active ? styles.dotActive : ''}`}
                    onClick={() => setActive(i)}
                    aria-label={`Go to testimonial ${i + 1}`}
                  />
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </section>
  );
}
