import { css } from '@emotion/react';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useGameStore } from '../../store/useGameStore';
import { TutorialProgressBar } from './TutorialProgressBar';
import { TutorialTooltip } from './TutorialTooltip';
import { TutorialWelcomeCard } from './TutorialWelcomeCard';

// 각 스텝별 data-tutorial 키와 메시지 정의
const STEP_CONFIG: Array<{
  dataKey: string;
  tab: 'elements' | 'evolution' | 'fusion';
  message: string;
  tooltipPosition: 'above' | 'below';
  nextLabel?: string;
}> = [
  // step 0: WelcomeCard (별도 처리)
  // step 1 (index 0)
  {
    dataKey: 'elements-first-card',
    tab: 'elements',
    message: '원소는 시간이 지날수록 자동으로 쌓여요. 강화하면 더 빨리 모여요!',
    tooltipPosition: 'below',
  },
  // step 2 (index 1)
  {
    dataKey: 'fusion-slot1',
    tab: 'fusion',
    message: '슬롯을 탭해서 원소를 선택하세요. 불 🔥 + 물 💧 조합을 해보세요!',
    tooltipPosition: 'above',
  },
  // step 3 (index 2)
  {
    dataKey: 'fusion-result',
    tab: 'fusion',
    message: '새로운 원소 발견! 42가지 조합이 더 있어요. 계속 탐험해보세요!',
    tooltipPosition: 'above',
    nextLabel: '좋아!',
  },
  // step 4 (index 3)
  {
    dataKey: 'elements-enhance-button',
    tab: 'evolution',
    message: '원소를 강화하면 자동 수집 속도가 빨라져요! 골드를 모아 강화해보세요.',
    tooltipPosition: 'above',
    nextLabel: '완료',
  },
];

const spotlightStyle = (rect: DOMRect) => css`
  position: fixed;
  top: ${rect.top - 8}px;
  left: ${rect.left - 8}px;
  width: ${rect.width + 16}px;
  height: ${rect.height + 16}px;
  border-radius: 12px;
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.65);
  z-index: 1000;
  pointer-events: none;

  /* 스포트라이트 pulse 애니메이션 */
  @keyframes spotlight-pulse {
    0%, 100% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.65), 0 0 0 2px #3182F6; }
    50% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.65), 0 0 0 4px #3182F6; }
  }
  animation: spotlight-pulse 1.5s ease-in-out infinite;
`;

const progressBarContainerStyle = css`
  position: fixed;
  top: 16px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 1003;
  pointer-events: none;
`;

const skipButtonStyle = css`
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 1004;
  background: none;
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 20px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  padding: 6px 14px;
  cursor: pointer;
`;

const completionBadgeStyle = css`
  position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  background: #3182f6;
  color: #ffffff;
  border-radius: 20px;
  padding: 12px 24px;
  font-size: 15px;
  font-weight: 700;
  z-index: 1005;
  white-space: nowrap;
  animation: badge-appear 0.4s ease-out;

  @keyframes badge-appear {
    from { opacity: 0; transform: translateX(-50%) scale(0.8); }
    to { opacity: 1; transform: translateX(-50%) scale(1); }
  }
`;

export function TutorialOverlay() {
  const {
    tutorialStep,
    tutorialCompleted,
    pendingOfflineReward,
    advanceTutorial,
    skipTutorial,
    setActiveTab,
  } = useGameStore();

  const [targetRect, setTargetRect] = useState<DOMRect | null>(null);
  const [showCompletionBadge, setShowCompletionBadge] = useState(false);
  const observerRef = useRef<MutationObserver | null>(null);

  // 튜토리얼 완료 배지 표시
  useEffect(() => {
    if (tutorialCompleted && tutorialStep === 5) {
      setShowCompletionBadge(true);
      const timer = setTimeout(() => setShowCompletionBadge(false), 3000);
      return () => clearTimeout(timer);
    }
  }, [tutorialCompleted, tutorialStep]);

  // data-tutorial 타겟 요소를 찾아 rect 업데이트
  const updateTargetRect = () => {
    if (tutorialStep === 0 || tutorialCompleted) return;
    const configIndex = tutorialStep - 1;
    const config = STEP_CONFIG[configIndex];
    if (!config) return;

    const el = document.querySelector(`[data-tutorial="${config.dataKey}"]`);
    if (el) {
      setTargetRect(el.getBoundingClientRect());
    } else {
      setTargetRect(null);
    }
  };

  useLayoutEffect(() => {
    if (tutorialStep === 0 || tutorialCompleted) return;
    const configIndex = tutorialStep - 1;
    const config = STEP_CONFIG[configIndex];
    if (!config) return;

    // 탭 강제 이동
    setActiveTab(config.tab);

    // DOM 변경 감지해서 타겟 rect 갱신
    updateTargetRect();
    observerRef.current?.disconnect();
    observerRef.current = new MutationObserver(updateTargetRect);
    observerRef.current.observe(document.body, { childList: true, subtree: true });

    const resizeHandler = () => updateTargetRect();
    window.addEventListener('resize', resizeHandler);

    return () => {
      observerRef.current?.disconnect();
      window.removeEventListener('resize', resizeHandler);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tutorialStep, tutorialCompleted]);

  // 완전히 완료된 경우 렌더링하지 않음
  if (tutorialCompleted && !showCompletionBadge) return null;
  if (pendingOfflineReward) return null;
  if (tutorialCompleted && showCompletionBadge) {
    return <div css={completionBadgeStyle}>🎁 환영 선물 지급! T2 원소 + 120G</div>;
  }

  // Step 0: 환영 카드
  if (tutorialStep === 0) {
    return <TutorialWelcomeCard onStart={advanceTutorial} />;
  }

  const configIndex = tutorialStep - 1;
  const config = STEP_CONFIG[configIndex];
  if (!config) return null;

  const isLastStep = tutorialStep === 4;

  const handleNext = () => {
    if (isLastStep) {
      setShowCompletionBadge(true);
    }
    advanceTutorial();
  };

  return (
    <>
      {/* 스포트라이트 */}
      {targetRect && <div css={spotlightStyle(targetRect)} />}

      {/* 진행 표시 바 */}
      <div css={progressBarContainerStyle}>
        <TutorialProgressBar step={tutorialStep} />
      </div>

      {/* 건너뛰기 버튼 (Step 2 이상) */}
      {tutorialStep >= 1 && (
        <button css={skipButtonStyle} onClick={skipTutorial}>
          건너뛰기
        </button>
      )}

      {/* 툴팁 */}
      <TutorialTooltip
        message={config.message}
        onNext={handleNext}
        onSkip={tutorialStep >= 1 ? skipTutorial : undefined}
        nextLabel={config.nextLabel}
        position={config.tooltipPosition}
        targetRect={targetRect}
      />
    </>
  );
}
