'use client';

import { useEffect, useRef, useState } from 'react';

interface Testimonial {
  id: number;
  name: string;
  role: string | null;
  company: string | null;
  text: string;
  image_url: string;
}

export default function Testimonials() {
  const [items, setItems] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [active, setActive] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    const base = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${base}/api/homepage/testimonials`)
      .then(r => r.json())
      .then(d => { if (d.success && Array.isArray(d.data)) setItems(d.data); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const startAuto = (list: Testimonial[]) => {
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setActive(prev => (prev >= list.length - 1 ? 0 : prev + 1));
    }, 4500);
  };
  const stopAuto = () => { if (intervalRef.current) clearInterval(intervalRef.current); };

  useEffect(() => {
    if (!items.length) return;
    startAuto(items);
    return () => stopAuto();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [items]);

  const goTo = (idx: number) => { stopAuto(); setActive(idx); startAuto(items); };
  const prev = () => goTo(active === 0 ? items.length - 1 : active - 1);
  const next = () => goTo(active === items.length - 1 ? 0 : active + 1);

  if (loading || !items.length) return null;

  const current = items[active];

  return (
    <section className="testimonials" id="testimonials">
      <div className="testi-bg-wrap">
        <div className="testi-bg-blob testi-blob-1" />
        <div className="testi-bg-blob testi-blob-2" />
      </div>
      <div className="container">

        <div className="section-header center">
          <div className="section-eyebrow">Voices of Trust</div>
          <h2 className="section-title">What Our Partners <em>Say</em></h2>
        </div>

        <div className="tc-card">
          {/* Top row: avatar · author · arrows */}
          <div className="tc-header">
            <div className="tc-avatar">
              <img src={current.image_url} alt={current.name} />
            </div>
            <div className="tc-author">
              <strong>{current.name}</strong>
              {(current.role || current.company) && (
                <span>{[current.role, current.company].filter(Boolean).join(' · ')}</span>
              )}
            </div>
            <div className="tc-arrows">
              <button className="tc-arrow" onClick={prev} aria-label="Previous">
                <i className="fas fa-chevron-left" />
              </button>
              <button className="tc-arrow" onClick={next} aria-label="Next">
                <i className="fas fa-chevron-right" />
              </button>
            </div>
          </div>

          {/* Quote */}
          <p className="tc-text" key={active}>&ldquo;{current.text}&rdquo;</p>

          {/* Dot indicators */}
          <div className="tc-dots">
            {items.map((_, i) => (
              <button
                key={i}
                className={`tc-dot${i === active ? ' active' : ''}`}
                onClick={() => goTo(i)}
                aria-label={`Testimonial ${i + 1}`}
              />
            ))}
          </div>
        </div>

      </div>
    </section>
  );
}
