"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import { SelectedBanner } from "@/app/components/SelectedBanner";
import Link from "next/link";
import useSWR from "swr";

type Banner = { id: string; title: string; imageUrl: string; linkUrl?: string | null };
type SubItem = { id: string; name: string; href: string };

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export function HeroBanner({ subItems, activeSubId }: { subItems?: SubItem[]; activeSubId?: string }) {
  // SWR 캐시 사용: 페이지 전환 시 재요청/깜빡임 최소화
  const { data } = useSWR<{ banners: Banner[] }>("/api/banners", fetcher, {
    revalidateOnFocus: false,
    dedupingInterval: 10 * 60 * 1000, // 10분 간 동일 요청 합치기
    keepPreviousData: true,
  });
  const banners = data?.banners ?? [];
  const [activeIndex, setActiveIndex] = useState(0);
  const [isHovered, setIsHovered] = useState(false);
  const [progress, setProgress] = useState(0); // 0..1
  const rotationMs = 5000;
  const rafIdRef = useRef<number | null>(null);
  const startedAtRef = useRef<number>(0);

  const numSlides = banners.length;
  const canAutoPlay = numSlides > 1 && !isHovered;

  const startTicker = useCallback(() => {
    if (!canAutoPlay) return;
    startedAtRef.current = performance.now();
    const tick = () => {
      const now = performance.now();
      const elapsed = now - startedAtRef.current;
      const nextProgress = Math.min(1, elapsed / rotationMs);
      setProgress(nextProgress);
      if (nextProgress >= 1) {
        setActiveIndex((i) => (i + 1) % Math.max(1, numSlides));
        startedAtRef.current = performance.now();
        setProgress(0);
      }
      rafIdRef.current = window.requestAnimationFrame(tick);
    };
    rafIdRef.current = window.requestAnimationFrame(tick);
  }, [canAutoPlay, numSlides, rotationMs]);

  const stopTicker = useCallback(() => {
    if (rafIdRef.current) {
      window.cancelAnimationFrame(rafIdRef.current);
      rafIdRef.current = null;
    }
  }, []);

  useEffect(() => {
    stopTicker();
    setProgress(0);
    startTicker();
    return () => stopTicker();
  }, [startTicker, stopTicker, activeIndex, isHovered, numSlides]);

  const goTo = useCallback((index: number) => {
    if (numSlides === 0) return;
    const next = (index + numSlides) % numSlides;
    setActiveIndex(next);
    setProgress(0);
    startedAtRef.current = performance.now();
  }, [numSlides]);

  const goPrev = useCallback(() => goTo(activeIndex - 1), [activeIndex, goTo]);
  const goNext = useCallback(() => goTo(activeIndex + 1), [activeIndex, goTo]);

  const translatePercent = useMemo(() => (numSlides > 0 ? -(activeIndex * 100) : 0), [activeIndex, numSlides]);

  if (numSlides === 0) {
    return (
      <section className="relative w-full overflow-hidden rounded-xl bg-neutral-900 text-white" aria-roledescription="carousel">
        <SelectedBanner className="h-56 sm:h-72 md:h-[264px]" />
        {/* 분리된 하단 블랙 바: 높이 58px, 중앙 서브카테고리 (스켈레톤 상태에서도 동일 레이아웃 유지) */}
        <div className="mt-2 h-[58px] bg-black rounded-xl flex items-center justify-center px-2">
          {Array.isArray(subItems) && subItems.length > 0 && (
            <div className="flex flex-wrap items-center gap-[8px]">
              {subItems.map((s) => (
                <Link
                  key={s.id}
                  href={s.href}
                  className={
                    s.id === activeSubId
                      ? "px-3 h-[28px] rounded-full bg-[#F94B37] text-white text-[12px] leading-[28px] whitespace-nowrap"
                      : "px-3 h-[28px] rounded-full bg-transparent text-white/85 hover:text-white border border-white/30 text-[12px] leading-[28px] whitespace-nowrap"
                  }
                >
                  {s.name}
                </Link>
              ))}
            </div>
          )}
        </div>
      </section>
    );
  }

  return (
    <section
      className="relative w-full overflow-hidden rounded-xl bg-neutral-900 text-white"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      aria-roledescription="carousel"
    >
      <div className="relative h-56 sm:h-72 md:h-[264px]">
        <div
          className="flex h-full w-full transition-transform duration-500 ease-out"
          style={{ transform: `translate3d(${translatePercent}%, 0, 0)`, width: `${numSlides * 100}%` }}
        >
          {banners.map((banner) => (
            <div key={banner.id} className="relative h-full w-full shrink-0">
              {banner.linkUrl ? (
                <a href={banner.linkUrl} className="block h-full w-full focus:outline-none focus:ring-2 focus:ring-white/60" aria-label={banner.title}>
                  <Image src={banner.imageUrl} alt={banner.title} fill priority className="object-cover" />
                </a>
              ) : (
                <Image src={banner.imageUrl} alt={banner.title} fill priority className="object-cover" />
              )}
              {/* Figma 스타일: 오버레이 제거 */}
              <div className="absolute bottom-3 left-4 right-4 md:bottom-5 md:left-6 md:right-6">
                <h2 className="line-clamp-2 text-lg font-semibold md:text-2xl">{banner.title}</h2>
              </div>
            </div>
          ))}
        </div>

        {/* Pagination - Figma 스타일: 활성은 주황 바, 비활성은 회색 점 (배너 위에 오버랩) */}
        {numSlides > 1 && (
          <div className="pointer-events-auto absolute bottom-3 left-1/2 -translate-x-1/2 z-10 flex items-center gap-[10px]">
            {banners.map((_, i) => (
              <button
                key={i}
                aria-label={`Go to slide ${i + 1}`}
                aria-current={activeIndex === i ? "true" : undefined}
                onClick={() => goTo(i)}
                className={
                  activeIndex === i
                    ? "h-[6px] w-[24px] rounded-full bg-[#F94B37]"
                    : "h-[10px] w-[10px] rounded-full bg-[rgba(255,255,255,0.7)] hover:bg-white"
                }
              />
            ))}
          </div>
        )}
      </div>

      {/* 분리된 하단 블랙 바: 높이 58px, 중앙 서브카테고리 */}
      <div className="mt-2 h-[58px] bg-black rounded-xl flex items-center justify-center px-2">
        {Array.isArray(subItems) && subItems.length > 0 && (
          <div className="flex flex-wrap items-center gap-[8px]">
              {subItems.map((s) => (
                <Link
                key={s.id}
                  href={s.href}
                className={
                  s.id === activeSubId
                    ? "px-3 h-[28px] rounded-full bg-[#F94B37] text-white text-[12px] leading-[28px] whitespace-nowrap"
                    : "px-3 h-[28px] rounded-full bg-transparent text-white/85 hover:text-white border border-white/30 text-[12px] leading-[28px] whitespace-nowrap"
                }
              >
                {s.name}
                </Link>
            ))}
          </div>
        )}
      </div>

      {/* Progress bar
      {numSlides > 1 && (
        <div className="absolute bottom-0 left-0 right-0 z-10 h-1 bg-white/20">
          <div className="h-full bg-white transition-[width] duration-100" style={{ width: `${progress * 100}%` }} />
        </div>
      )} */}

      
    </section>
  );
}


