'use client';

import { useCallback, useEffect, useRef } from 'react';
import type { Testimonial } from '@/types';
import Multiline from '@/components/common/Multiline';
import { testimonialCarouselInterval, type TestimonialAutoplaySpeed } from '@/lib/home/testimonials';
import { useBootstrapCarousel } from '@/lib/hooks/useBootstrapCarousel';

/** "What Leaders Say": the quote carousel drives a paired image carousel and keeps a constant height. */
export default function LeadersCarousel({
  testimonials,
  autoplaySpeed = 'normal',
  showArrows = true,
}: {
  testimonials: Testimonial[];
  autoplaySpeed?: TestimonialAutoplaySpeed;
  showArrows?: boolean;
}) {
  const textRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLDivElement>(null);
  const innerRef = useRef<HTMLDivElement>(null);
  const interval = testimonialCarouselInterval(autoplaySpeed);
  const autoplay = interval !== false;

  const equaliseHeight = useCallback(() => {
    const inner = innerRef.current;
    if (!inner) return;
    inner.style.height = 'auto';
    let max = 0;
    inner.querySelectorAll<HTMLElement>('.carousel-item').forEach((item) => {
      const { display, visibility } = item.style;
      item.style.display = 'block';
      item.style.visibility = 'hidden';
      max = Math.max(max, item.offsetHeight);
      item.style.display = display;
      item.style.visibility = visibility;
    });
    inner.style.height = `${max}px`;
  }, []);

  useEffect(() => {
    equaliseHeight();
    window.addEventListener('load', equaliseHeight);
    window.addEventListener('resize', equaliseHeight);
    document.fonts?.ready.then(equaliseHeight);
    return () => {
      window.removeEventListener('load', equaliseHeight);
      window.removeEventListener('resize', equaliseHeight);
    };
  }, [equaliseHeight, testimonials]);

  useBootstrapCarousel(imageRef, { autoplay: false });
  useBootstrapCarousel(
    textRef,
    { autoplay, interval: interval || false },
    () => {
      const text = textRef.current;
      if (!text) return;
      const sync = (e: Event) => {
        const image = imageRef.current;
        if (!image) return;
        import('bootstrap').then(({ Carousel }) => {
          Carousel.getOrCreateInstance(image, { interval: false, ride: false }).to((e as Event & { to: number }).to);
        });
      };
      text.addEventListener('slide.bs.carousel', sync);
      return () => text.removeEventListener('slide.bs.carousel', sync);
    },
  );

  return (
    <section className="py-5 bg-black position-relative overflow-hidden leaders-section">
      <div className="container position-relative">
        <div className="wl-grid">
          <div className="wl-heading pe-lg-3">
            <h2 className="section-title mb-0">
              WHAT
              <br />
              <span className="text-golden mb-0">LEADERS SAY</span>
            </h2>
          </div>

          <div className="wl-text pe-lg-3">
            <div
              id="whatLeadersTextCarousel"
              ref={textRef}
              className="carousel slide flex-grow-1 d-flex flex-column justify-content-start"
              data-bs-interval={autoplay ? interval : 'false'}
            >
              <div className="carousel-inner pb-lg-3" ref={innerRef}>
                {testimonials.map((t, i) => (
                  <div className={`carousel-item${i === 0 ? ' active' : ''}`} key={t.id}>
                    <p className="what-leaders-content-text fw-300 mb-3 fst-italic color-white-same">
                      <Multiline text={t.quote} />
                    </p>
                    {t.author && <p className="text-md color-white fw-bold mb-0">{t.author}</p>}
                  </div>
                ))}
              </div>
              {showArrows && testimonials.length > 1 && (
                <>
                  <button
                    className="carousel-control-prev leaders-carousel-control"
                    type="button"
                    data-bs-target="#whatLeadersTextCarousel"
                    data-bs-slide="prev"
                  >
                    <span className="carousel-control-prev-icon" aria-hidden="true" />
                    <span className="visually-hidden">Previous quote</span>
                  </button>
                  <button
                    className="carousel-control-next leaders-carousel-control"
                    type="button"
                    data-bs-target="#whatLeadersTextCarousel"
                    data-bs-slide="next"
                  >
                    <span className="carousel-control-next-icon" aria-hidden="true" />
                    <span className="visually-hidden">Next quote</span>
                  </button>
                </>
              )}
            </div>
          </div>

          <div className="wl-image ps-lg-3">
            <div id="whatLeadersImageCarousel" ref={imageRef} className="carousel slide h-100">
              <div className="carousel-inner h-100">
                {testimonials.map((t, i) => (
                  <div className={`carousel-item${i === 0 ? ' active' : ''} h-100`} key={`${t.id}-${t.image}`}>
                    <img src={t.image} alt={t.author ?? 'CMORoom guest'} className="w-100 h-100 object-fit-cover" />
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
