'use client';

import { useRef, type ReactNode } from 'react';
import InsightNavLink from './InsightNavLink';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination } from 'swiper/modules';
import type { NavigationOptions } from 'swiper/types';
import type { Swiper as SwiperInstance } from 'swiper';
import 'swiper/css';
import 'swiper/css/navigation';
import '@/styles/owl-compat.css';
import type { InsightFeatureCard } from '@/types';
import FeatureCardBody from './FeatureCardBody';

const CARD_CLASS =
  'insight-card-type-1 text-decoration-none d-block bg-color-white overflow-hidden w-100 shadow-sm h-100';

function slideTarget(slide: InsightFeatureCard): string {
  if (slide.href) return slide.href;
  // Roundup cards mirror the numbered stories below — jump to that story.
  return `#insight-story-${slide.number}`;
}

function SlideLink({ slide, children }: { slide: InsightFeatureCard; children: ReactNode }) {
  const target = slideTarget(slide);

  if (target.startsWith('#')) {
    return (
      <a href={target} className={CARD_CLASS}>
        {children}
      </a>
    );
  }

  if (/^https?:\/\//i.test(target)) {
    return (
      <a href={target} target="_blank" rel="noopener noreferrer" className={CARD_CLASS}>
        {children}
      </a>
    );
  }

  return (
    <InsightNavLink href={target} className={CARD_CLASS}>
      {children}
    </InsightNavLink>
  );
}

/** Featured-card slider: 1-up mobile / 2-up desktop, optional arrows + dots. */
export default function ArticleSlider({
  slides,
  showArrows = true,
}: {
  slides: InsightFeatureCard[];
  /** @deprecated Cards use each slide's own href / story anchor; kept for call-site compatibility. */
  href?: string;
  showArrows?: boolean;
}) {
  const prevRef = useRef<HTMLButtonElement>(null);
  const nextRef = useRef<HTMLButtonElement>(null);

  // Desktop shows 2-up — dots only when there is a second page of cards.
  const showDots = slides.length > 2;
  const canNavigate = showArrows && slides.length > 1;

  return (
    <div className="article-slider-wrap position-relative">
      {canNavigate && (
        <>
          <button
            ref={prevRef}
            type="button"
            className="article-slider-nav article-slider-nav-prev"
            aria-label="Previous cards"
          >
            <span aria-hidden="true">‹</span>
          </button>
          <button
            ref={nextRef}
            type="button"
            className="article-slider-nav article-slider-nav-next"
            aria-label="Next cards"
          >
            <span aria-hidden="true">›</span>
          </button>
        </>
      )}
      <Swiper
        className="owl-theme article-slider-container pb-2"
        modules={[...(canNavigate ? [Navigation] : []), ...(showDots ? [Pagination] : [])]}
        loop={slides.length > 2}
        watchOverflow
        spaceBetween={20}
        slidesPerView={1}
        breakpoints={{
          768: {
            slidesPerView: Math.min(2, slides.length),
            slidesPerGroup: Math.min(2, slides.length),
          },
        }}
        onBeforeInit={(swiper: SwiperInstance) => {
          if (!canNavigate) return;
          const nav = swiper.params.navigation;
          if (nav && typeof nav !== 'boolean') {
            const options = nav as NavigationOptions;
            options.prevEl = prevRef.current;
            options.nextEl = nextRef.current;
          }
        }}
        navigation={canNavigate}
        pagination={
          showDots
            ? {
                clickable: true,
                bulletClass: 'owl-dot',
                bulletActiveClass: 'active',
                renderBullet: (_index, className) =>
                  `<button type="button" role="button" class="${className}"><span></span></button>`,
              }
            : false
        }
      >
        {slides.map((slide) => (
          <SwiperSlide key={`${slide.number}-${slide.title}`}>
            <div className="article-slider-item">
              <SlideLink slide={slide}>
                <div className="p-4 position-relative">
                  <FeatureCardBody card={slide} logoClassName="img-fluid w-auto" />
                </div>
              </SlideLink>
            </div>
          </SwiperSlide>
        ))}
        {showDots ? <div slot="container-end" className="owl-dots"></div> : null}
      </Swiper>
    </div>
  );
}
