import { useCallback, useEffect, useRef, useMemo } from 'react';

export interface CarouselItem {
  key: string | number;
  src: string;
}

interface ThumbnailCarouselProps {
  items: CarouselItem[];
  activeIndex: number;
  onSelect: (index: number) => void;
  className?: string;
}

/** 한 번에 표시할 최대 슬롯 수 */
const MAX_VISIBLE = 5;
/** 드래그 시 인덱스 1칸 이동에 필요한 px */
const DRAG_STEP = 50;
/** 휠 누적 임계값 */
const WHEEL_THRESHOLD = 40;

/** 슬롯 크기/투명도 — 중앙에서의 거리 기반 */
const SLOT_STYLES: Record<number, { w: number; h: number; opacity: number }> = {
  0: { w: 64, h: 48, opacity: 1 },
  1: { w: 52, h: 40, opacity: 0.7 },
  2: { w: 44, h: 34, opacity: 0.5 },
};

/** 링 형태 슬롯 계산: activeIndex 중앙, 좌우 wrap-around */
function ringSlots(active: number, total: number): { idx: number; pos: number }[] {
  if (total <= 0) return [];
  if (total === 1) return [{ idx: 0, pos: 0 }];
  // 2장: 중앙 + 우측
  if (total === 2) return [{ idx: active, pos: 0 }, { idx: (active + 1) % 2, pos: 1 }];

  const half = Math.min(Math.floor(MAX_VISIBLE / 2), Math.floor(total / 2));
  const slots: { idx: number; pos: number }[] = [];
  const seen = new Set<number>();
  for (let offset = -half; offset <= half; offset++) {
    const idx = ((active + offset) % total + total) % total;
    if (seen.has(idx)) continue;
    seen.add(idx);
    slots.push({ idx, pos: offset });
  }
  return slots;
}

/**
 * 링 형태 무한 썸네일 캐러셀.
 * - 5개 고정 슬롯 (중앙 = 활성, 좌우 2장씩)
 * - 모듈러 인덱싱으로 끝↔처음 무한 순환
 * - 마우스 드래그 + 휠로 연속 탐색 (주르륵)
 * - Tailwind CSS 기반, 재사용 가능
 */
export function ThumbnailCarousel({ items, activeIndex, onSelect, className }: ThumbnailCarouselProps) {
  const total = items.length;
  const containerRef = useRef<HTMLDivElement>(null);
  const activeRef = useRef(activeIndex);
  useEffect(() => { activeRef.current = activeIndex; }, [activeIndex]);
  const dragRef = useRef({ active: false, startX: 0, startIndex: 0, lastSteps: 0 });

  const slots = useMemo(() => ringSlots(activeIndex, total), [activeIndex, total]);

  // ── 드래그: 연속 인덱스 이동 ──
  const onMouseDown = useCallback((e: React.MouseEvent) => {
    dragRef.current = { active: true, startX: e.pageX, startIndex: activeRef.current, lastSteps: 0 };
    if (containerRef.current) containerRef.current.style.cursor = 'grabbing';
  }, []);

  const onMouseMove = useCallback((e: React.MouseEvent) => {
    if (!dragRef.current.active) return;
    e.preventDefault();
    const dx = e.pageX - dragRef.current.startX;
    const steps = Math.round(-dx / DRAG_STEP);
    if (steps !== dragRef.current.lastSteps) {
      dragRef.current.lastSteps = steps;
      onSelect(((dragRef.current.startIndex + steps) % total + total) % total);
    }
  }, [total, onSelect]);

  const onMouseUp = useCallback(() => {
    dragRef.current.active = false;
    if (containerRef.current) containerRef.current.style.cursor = '';
  }, []);

  // ── 휠: 누적 기반 인덱스 이동 ──
  useEffect(() => {
    const c = containerRef.current;
    if (!c) return;
    let acc = 0;
    const onWheel = (e: WheelEvent) => {
      e.preventDefault();
      acc += Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
      if (Math.abs(acc) >= WHEEL_THRESHOLD) {
        const dir = acc > 0 ? 1 : -1;
        acc = 0;
        const cur = activeRef.current;
        onSelect(((cur + dir) % total + total) % total);
      }
    };
    c.addEventListener('wheel', onWheel, { passive: false });
    return () => c.removeEventListener('wheel', onWheel);
  }, [total, onSelect]);

  if (total <= 1) return null;

  return (
    <div
      ref={containerRef}
      className={[
        'flex items-center justify-center gap-2 py-2.5',
        'select-none cursor-grab',
        'border-t border-[var(--wing-subtle)]',
        className,
      ].filter(Boolean).join(' ')}
      onMouseDown={onMouseDown}
      onMouseMove={onMouseMove}
      onMouseUp={onMouseUp}
      onMouseLeave={onMouseUp}
    >
      {slots.map(({ idx, pos }) => {
        const { w, h, opacity } = SLOT_STYLES[Math.abs(pos)] ?? SLOT_STYLES[2];
        const isActive = pos === 0;
        return (
          <button
            key={idx}
            className={[
              'shrink-0 rounded-md overflow-hidden border-2 p-0',
              'transition-all duration-200 ease-out',
              'bg-[var(--wing-subtle)]',
              isActive
                ? 'border-[var(--accent)]'
                : 'border-transparent hover:opacity-100 hover:border-[var(--accent)]',
            ].join(' ')}
            style={{ width: w, height: h, opacity }}
            onClick={() => onSelect(idx)}
          >
            <img
              src={items[idx].src}
              alt=""
              className="block w-full h-full object-cover pointer-events-none"
              draggable={false}
            />
          </button>
        );
      })}
    </div>
  );
}
