/* global React, ReactDOM */

const { useState, useRef, useEffect, useCallback } = React;

// ---- Inline icons (no external library) ----
const ClockIcon = (props) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <circle cx="12" cy="12" r="10" />
    <polyline points="12 6 12 12 16 14" />
  </svg>
);

const TrendingUpIcon = (props) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <polyline points="22 7 13.5 15.5 8.5 10.5 2 17" />
    <polyline points="16 7 22 7 22 13" />
  </svg>
);

const CalendarIcon = (props) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
    <line x1="16" y1="2" x2="16" y2="6" />
    <line x1="8" y1="2" x2="8" y2="6" />
    <line x1="3" y1="10" x2="21" y2="10" />
  </svg>
);

// ---- Generic placeholder testimonials ----
const TESTIMONIALS = [
  {
    id: 1,
    initials: 'SM',
    name: 'Sarah M.',
    role: 'Owner — Local Veterinary Clinic',
    quote: "Afton built an after-hours system that books appointments overnight. We used to lose four or five a week to missed voicemails. Now they're all on the calendar by morning.",
    tags: [
      { text: 'Voice agent', type: 'featured' },
      { text: 'After-hours', type: 'default' },
    ],
    stats: [
      { icon: ClockIcon, text: '9 hrs/week back' },
      { icon: CalendarIcon, text: 'Live since March' },
    ],
    avatarGradient: 'linear-gradient(135deg, #6b21a8 0%, #a855f7 100%)',
  },
  {
    id: 2,
    initials: 'JK',
    name: 'James K.',
    role: 'Founder — Tax & Bookkeeping Practice',
    quote: "Client onboarding went from forty-five minutes a head down to about eight. I can finally take on the work I was turning away every quarter.",
    tags: [
      { text: 'Workflow', type: 'featured' },
      { text: 'Quick Win', type: 'default' },
    ],
    stats: [
      { icon: ClockIcon, text: '37 min/client back' },
      { icon: TrendingUpIcon, text: '2-week build' },
    ],
    avatarGradient: 'linear-gradient(135deg, #a855f7 0%, #c9847a 100%)',
  },
  {
    id: 3,
    initials: 'PR',
    name: 'Priya R.',
    role: 'Owner — Boutique Travel Agency',
    quote: "I was skeptical AI could write itineraries my clients would actually use. Two months in, my repeat rate is up and I'm spending evenings with my family again.",
    tags: [
      { text: 'AI agent', type: 'featured' },
      { text: 'Custom build', type: 'default' },
    ],
    stats: [
      { icon: ClockIcon, text: '12 hrs/week back' },
      { icon: TrendingUpIcon, text: 'Repeat rate up' },
    ],
    avatarGradient: 'linear-gradient(135deg, #c9847a 0%, #6b21a8 100%)',
  },
];

// ---- TestimonialStack (converted from the supplied TS source) ----
const TestimonialStack = ({ testimonials, visibleBehind = 2 }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState(0);
  const dragStartRef = useRef(0);
  const cardRefs = useRef([]);
  const totalCards = testimonials.length;

  const navigate = useCallback((newIndex) => {
    setActiveIndex((newIndex + totalCards) % totalCards);
  }, [totalCards]);

  const handleDragStart = (e, index) => {
    if (index !== activeIndex) return;
    setIsDragging(true);
    const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
    dragStartRef.current = clientX;
    cardRefs.current[activeIndex]?.classList.add('is-dragging');
  };

  const handleDragMove = useCallback((e) => {
    if (!isDragging) return;
    const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
    setDragOffset(clientX - dragStartRef.current);
  }, [isDragging]);

  const handleDragEnd = useCallback(() => {
    if (!isDragging) return;
    cardRefs.current[activeIndex]?.classList.remove('is-dragging');
    if (Math.abs(dragOffset) > 50) {
      navigate(activeIndex + (dragOffset < 0 ? 1 : -1));
    }
    setIsDragging(false);
    setDragOffset(0);
  }, [isDragging, dragOffset, activeIndex, navigate]);

  useEffect(() => {
    if (isDragging) {
      window.addEventListener('mousemove', handleDragMove);
      window.addEventListener('touchmove', handleDragMove);
      window.addEventListener('mouseup', handleDragEnd);
      window.addEventListener('touchend', handleDragEnd);
    }
    return () => {
      window.removeEventListener('mousemove', handleDragMove);
      window.removeEventListener('touchmove', handleDragMove);
      window.removeEventListener('mouseup', handleDragEnd);
      window.removeEventListener('touchend', handleDragEnd);
    };
  }, [isDragging, handleDragMove, handleDragEnd]);

  if (!testimonials?.length) return null;

  return (
    <section className="testimonials-stack">
      {testimonials.map((testimonial, index) => {
        const displayOrder = (index - activeIndex + totalCards) % totalCards;

        const style = {};
        if (displayOrder === 0) {
          style.transform = `translateX(${dragOffset}px)`;
          style.opacity = 1;
          style.zIndex = totalCards;
        } else if (displayOrder <= visibleBehind) {
          const scale = 1 - 0.05 * displayOrder;
          const translateY = -1.5 * displayOrder; // rem
          style.transform = `scale(${scale}) translateY(${translateY}rem)`;
          style.opacity = 1 - 0.25 * displayOrder;
          style.zIndex = totalCards - displayOrder;
        } else {
          style.transform = 'scale(0.85)';
          style.opacity = 0;
          style.zIndex = 0;
          style.pointerEvents = 'none';
        }

        return (
          <div
            ref={(el) => (cardRefs.current[index] = el)}
            key={testimonial.id}
            className="testimonial-card"
            style={style}
            onMouseDown={(e) => handleDragStart(e, index)}
            onTouchStart={(e) => handleDragStart(e, index)}
          >
            <div className="t-inner">
              <div className="t-head">
                <div
                  className="t-avatar"
                  style={{ background: testimonial.avatarGradient }}
                  aria-hidden="true"
                >
                  {testimonial.initials}
                </div>
                <div>
                  <h3 className="t-name">{testimonial.name}</h3>
                  <p className="t-role">{testimonial.role}</p>
                </div>
              </div>

              <blockquote className="t-quote">"{testimonial.quote}"</blockquote>

              <div className="t-foot">
                <div className="t-tags">
                  {testimonial.tags.map((tag, i) => (
                    <span
                      key={i}
                      className={`t-tag ${tag.type === 'featured' ? 't-tag-featured' : 't-tag-default'}`}
                    >
                      {tag.text}
                    </span>
                  ))}
                </div>
                <div className="t-stats">
                  {testimonial.stats.map((stat, i) => {
                    const Icon = stat.icon;
                    return (
                      <span key={i} className="t-stat">
                        <Icon />
                        {stat.text}
                      </span>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
        );
      })}

      <div className="t-pagination">
        {testimonials.map((_, index) => (
          <button
            key={index}
            type="button"
            aria-label={`Go to testimonial ${index + 1}`}
            onClick={() => navigate(index)}
            className={`t-dot ${activeIndex === index ? 'is-active' : ''}`}
          />
        ))}
      </div>
    </section>
  );
};

const mount = document.getElementById('testimonials-stack-root');
if (mount) {
  ReactDOM.createRoot(mount).render(<TestimonialStack testimonials={TESTIMONIALS} />);
}
