'use client';

import { useRef, useEffect, useState } from 'react';

interface UseSwipeableTabsOptions {
  tabs: string[];
  activeIndex: number;
  onTabChange: (index: number) => void;
  enabled?: boolean;
}

export function useSwipeableTabs({ tabs, activeIndex, onTabChange, enabled = true }: UseSwipeableTabsOptions) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const touchStartRef = useRef<{ x: number; y: number; time: number } | null>(null);
  const directionLockedRef = useRef<'horizontal' | 'vertical' | null>(null);

  // Touch handlers
  useEffect(() => {
    const container = containerRef.current;
    if (!container || !enabled) return;

    const handleTouchStart = (e: TouchEvent) => {
      // 에디터 영역에서는 스와이프 차단
      const target = e.target as HTMLElement;
      if (target.closest('.ProseMirror') || target.closest('[data-no-swipe]')) {
        return;
      }

      if (isTransitioning) return;

      touchStartRef.current = {
        x: e.touches[0].clientX,
        y: e.touches[0].clientY,
        time: Date.now(),
      };
      directionLockedRef.current = null;
    };

    const handleTouchMove = (e: TouchEvent) => {
      if (!touchStartRef.current) return;

      const deltaX = e.touches[0].clientX - touchStartRef.current.x;
      const deltaY = e.touches[0].clientY - touchStartRef.current.y;

      // 방향 판정 (한번만)
      if (!directionLockedRef.current) {
        const absX = Math.abs(deltaX);
        const absY = Math.abs(deltaY);

        if (absX < 10 && absY < 10) return; // 최소 이동 거리

        // 각도 30° 기준: tan(30°) ≈ 0.577
        // deltaY/deltaX > tan(30°) → 세로 스크롤
        const angle = Math.atan2(absY, absX) * (180 / Math.PI);
        directionLockedRef.current = angle > 30 ? 'vertical' : 'horizontal';
      }

      if (directionLockedRef.current === 'vertical') return;

      // 수평 스와이프: 기본 스크롤 방지
      e.preventDefault();
    };

    const handleTouchEnd = (e: TouchEvent) => {
      if (!touchStartRef.current || directionLockedRef.current === 'vertical') {
        touchStartRef.current = null;
        directionLockedRef.current = null;
        return;
      }

      const deltaX = e.changedTouches[0].clientX - touchStartRef.current.x;
      const deltaTime = Date.now() - touchStartRef.current.time;
      const velocity = Math.abs(deltaX) / deltaTime; // px/ms

      const threshold = container.offsetWidth * 0.3;
      const velocityThreshold = 0.3; // px/ms

      let newIndex = activeIndex;

      if (deltaX < -threshold || (deltaX < -30 && velocity > velocityThreshold)) {
        // 왼쪽으로 스와이프 → 다음 탭
        newIndex = Math.min(activeIndex + 1, tabs.length - 1);
      } else if (deltaX > threshold || (deltaX > 30 && velocity > velocityThreshold)) {
        // 오른쪽으로 스와이프 → 이전 탭
        newIndex = Math.max(activeIndex - 1, 0);
      }

      if (newIndex !== activeIndex) {
        setIsTransitioning(true);
        onTabChange(newIndex);
        setTimeout(() => setIsTransitioning(false), 300);
      }

      touchStartRef.current = null;
      directionLockedRef.current = null;
    };

    container.addEventListener('touchstart', handleTouchStart, { passive: true });
    container.addEventListener('touchmove', handleTouchMove, { passive: false });
    container.addEventListener('touchend', handleTouchEnd, { passive: true });

    return () => {
      container.removeEventListener('touchstart', handleTouchStart);
      container.removeEventListener('touchmove', handleTouchMove);
      container.removeEventListener('touchend', handleTouchEnd);
    };
  }, [enabled, activeIndex, tabs.length, onTabChange, isTransitioning]);

  return { containerRef, isTransitioning };
}
