import { css, keyframes } from '@emotion/react';
import { useState, useRef } from 'react';
import { adaptive } from '../styles/adaptive';
import { useGameStore } from '../store/useGameStore';
import prestigeTableData from '../data/prestige.json';

// ────────────────────────────────────────────────────────────
// Prestige table
// ────────────────────────────────────────────────────────────

interface PrestigeEntry {
  count: number;
  goldMultiplier: number;
  spawnMultiplier: number;
  starterGold: number;
  title: string;
  titleEmoji: string;
  titleColor: string;
}

const PRESTIGE_TABLE = prestigeTableData as PrestigeEntry[];

function getNextEntry(currentCount: number): PrestigeEntry {
  const nextCount = currentCount + 1;
  const entry = PRESTIGE_TABLE.find((e) => e.count === nextCount);
  if (!entry) {
    const last = PRESTIGE_TABLE[PRESTIGE_TABLE.length - 1];
    const over = nextCount - last.count;
    return {
      count: nextCount,
      goldMultiplier: parseFloat((last.goldMultiplier + 0.5 * over).toFixed(1)),
      spawnMultiplier: parseFloat((last.spawnMultiplier + 0.1 * over).toFixed(1)),
      starterGold: last.starterGold + 5000 * over,
      title: '원소의 주인',
      titleEmoji: '🌌',
      titleColor: '#9C27B0',
    };
  }
  return entry;
}

// ────────────────────────────────────────────────────────────
// Particle animation
// ────────────────────────────────────────────────────────────

const particleFloat = keyframes`
  0%   { transform: translateY(0) scale(1);   opacity: 1; }
  100% { transform: translateY(-100vh) scale(0); opacity: 0; }
`;

const screenFlash = keyframes`
  0%   { opacity: 0; }
  20%  { opacity: 0.8; }
  100% { opacity: 0; }
`;

const titleReveal = keyframes`
  0%   { transform: scale(0.5) translateY(40px); opacity: 0; }
  60%  { transform: scale(1.1) translateY(-8px); opacity: 1; }
  100% { transform: scale(1) translateY(0);     opacity: 1; }
`;

const fadeInUp = keyframes`
  0%   { transform: translateY(60px); opacity: 0; }
  100% { transform: translateY(0);    opacity: 1; }
`;

// ────────────────────────────────────────────────────────────
// Styles
// ────────────────────────────────────────────────────────────

const overlayStyle = css`
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.75);
  z-index: 300;
  display: flex;
  align-items: flex-end;
`;

const modalStyle = css`
  width: 100%;
  background: ${adaptive.background};
  border-radius: 24px 24px 0 0;
  padding: 24px 20px 40px;
  animation: ${fadeInUp} 0.3s ease-out;
`;

const handleStyle = css`
  width: 40px;
  height: 4px;
  background: ${adaptive.grey300};
  border-radius: 2px;
  margin: 0 auto 20px;
`;

const modalTitleStyle = css`
  font-size: 20px;
  font-weight: 700;
  color: #ff6f00;
  margin: 0 0 4px;
`;

const modalSubtitleStyle = css`
  font-size: 13px;
  color: ${adaptive.grey500};
  margin: 0 0 20px;
`;

const sectionLabelStyle = css`
  font-size: 12px;
  font-weight: 700;
  color: ${adaptive.grey500};
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 8px;
`;

const resetListStyle = css`
  background: #fff3e0;
  border: 1px solid #ffcc80;
  border-radius: 12px;
  padding: 12px 14px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 6px;
`;

const resetItemStyle = css`
  font-size: 13px;
  color: #e65100;
  display: flex;
  align-items: center;
  gap: 6px;
`;

const bonusCardStyle = css`
  background: linear-gradient(135deg, #1a0a00, #3d1a00);
  border: 1.5px solid #ffd700;
  border-radius: 14px;
  padding: 14px 16px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const bonusRowStyle = css`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const bonusLabelStyle = css`
  font-size: 13px;
  color: #ffcc80;
`;

const bonusValueStyle = css`
  font-size: 14px;
  font-weight: 700;
  color: #ffd700;
`;

const titlePreviewStyle = css`
  background: linear-gradient(135deg, #311b92, #512da8);
  border: 1px solid #7c4dff;
  border-radius: 12px;
  padding: 12px 14px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
`;

const titleEmojiStyle = css`
  font-size: 28px;
`;

const titleTextStyle = css`
  font-size: 15px;
  font-weight: 700;
  color: #e8d5ff;
`;

const titleSubStyle = css`
  font-size: 11px;
  color: #b39ddb;
  margin-top: 2px;
`;

const buttonRowStyle = css`
  display: flex;
  gap: 10px;
`;

const cancelButtonStyle = css`
  flex: 1;
  padding: 14px;
  border-radius: 12px;
  background: ${adaptive.greyBackground};
  color: ${adaptive.grey700};
  font-size: 15px;
  font-weight: 600;
  border: none;
  cursor: pointer;
`;

const confirmButtonStyle = (disabled: boolean) => css`
  flex: 2;
  padding: 14px;
  border-radius: 12px;
  background: ${disabled
    ? adaptive.grey200
    : 'linear-gradient(135deg, #ff6f00, #ffd700)'};
  color: ${disabled ? adaptive.grey400 : '#3d1a00'};
  font-size: 15px;
  font-weight: 700;
  border: none;
  cursor: ${disabled ? 'not-allowed' : 'pointer'};
  box-shadow: ${disabled ? 'none' : '0 4px 16px rgba(255, 180, 0, 0.4)'};
`;

// ────────────────────────────────────────────────────────────
// Particle layer
// ────────────────────────────────────────────────────────────

interface Particle {
  id: number;
  x: number;
  delay: number;
  duration: number;
  size: number;
  emoji: string;
}

const PARTICLE_EMOJIS = ['✨', '⭐', '🌟', '💫', '🔥', '💛', '🌙'];

function generateParticles(count: number): Particle[] {
  return Array.from({ length: count }, (_, i) => ({
    id: i,
    x: Math.random() * 100,
    delay: Math.random() * 1.5,
    duration: 1.5 + Math.random() * 1.5,
    size: 14 + Math.random() * 18,
    emoji: PARTICLE_EMOJIS[Math.floor(Math.random() * PARTICLE_EMOJIS.length)],
  }));
}

const particleLayerStyle = css`
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: 400;
  overflow: hidden;
`;

const flashLayerStyle = css`
  position: fixed;
  inset: 0;
  background: radial-gradient(circle at 50% 40%, #ffd700 0%, #ff6f00 60%, transparent 100%);
  z-index: 390;
  pointer-events: none;
  animation: ${screenFlash} 1.2s ease-out forwards;
`;

// ────────────────────────────────────────────────────────────
// Title unlock popup
// ────────────────────────────────────────────────────────────

interface TitlePopupProps {
  entry: PrestigeEntry;
  onDismiss: () => void;
}

const titlePopupOverlayStyle = css`
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.9);
  z-index: 500;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
`;

const titlePopupCardStyle = css`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  animation: ${titleReveal} 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
`;

const titlePopupEmojiStyle = css`
  font-size: 72px;
`;

const titlePopupHeadingStyle = css`
  font-size: 14px;
  color: #ffcc80;
  letter-spacing: 2px;
  text-transform: uppercase;
`;

const titlePopupNameStyle = css`
  font-size: 28px;
  font-weight: 800;
  color: #ffd700;
  text-align: center;
  text-shadow: 0 0 30px rgba(255, 215, 0, 0.8);
`;

const titlePopupDismissStyle = css`
  margin-top: 24px;
  padding: 12px 32px;
  border-radius: 24px;
  background: rgba(255, 215, 0, 0.15);
  border: 1px solid rgba(255, 215, 0, 0.4);
  color: #ffd700;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  animation: ${fadeInUp} 0.4s ease-out 1s both;
`;

function TitlePopup({ entry, onDismiss }: TitlePopupProps) {
  const [particles] = useState(() => generateParticles(40));

  return (
    <>
      <div css={flashLayerStyle} />
      <div css={particleLayerStyle}>
        {particles.map((p) => (
          <span
            key={p.id}
            css={css`
              position: absolute;
              left: ${p.x}%;
              bottom: -10px;
              font-size: ${p.size}px;
              animation: ${particleFloat} ${p.duration}s ${p.delay}s ease-out both;
            `}
          >
            {p.emoji}
          </span>
        ))}
      </div>
      <div css={titlePopupOverlayStyle} onClick={onDismiss}>
        <div css={titlePopupCardStyle}>
          <div css={titlePopupEmojiStyle}>{entry.titleEmoji}</div>
          <div css={titlePopupHeadingStyle}>✨ 칭호 잠금해제 ✨</div>
          <div css={titlePopupNameStyle}>{entry.title}</div>
        </div>
        <button css={titlePopupDismissStyle} onClick={onDismiss}>
          확인
        </button>
      </div>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// PrestigeModal
// ────────────────────────────────────────────────────────────

interface PrestigeModalProps {
  onClose: () => void;
}

export function PrestigeModal({ onClose }: PrestigeModalProps) {
  const prestigeCount = useGameStore((s) => s.prestigeCount);
  const prestige = useGameStore((s) => s.prestige);
  const elements = useGameStore((s) => s.elements);

  const [confirming, setConfirming] = useState(false);
  const [showParticles, setShowParticles] = useState(false);
  const [showTitlePopup, setShowTitlePopup] = useState(false);
  const completedEntry = useRef<PrestigeEntry | null>(null);
  const [particles] = useState(() => generateParticles(60));

  const nextEntry = getNextEntry(prestigeCount);

  const canConfirm =
    (elements['creation'] ?? 0) >= 1 && (elements['spirit'] ?? 0) >= 1;

  const handleConfirm = () => {
    if (!canConfirm || confirming) return;
    setConfirming(true);
    setShowParticles(true);

    // 약간의 딜레이 후 실제 prestige 실행 (연출 효과용)
    setTimeout(() => {
      const result = prestige();
      if (result.success) {
        completedEntry.current = nextEntry;
        setTimeout(() => {
          setShowParticles(false);
          setShowTitlePopup(true);
        }, 2000);
      } else {
        setShowParticles(false);
        setConfirming(false);
      }
    }, 500);
  };

  const handleTitleDismiss = () => {
    setShowTitlePopup(false);
    onClose();
  };

  if (showTitlePopup && completedEntry.current) {
    return <TitlePopup entry={completedEntry.current} onDismiss={handleTitleDismiss} />;
  }

  return (
    <>
      {showParticles && (
        <>
          <div css={flashLayerStyle} />
          <div css={particleLayerStyle}>
            {particles.map((p) => (
              <span
                key={p.id}
                css={css`
                  position: absolute;
                  left: ${p.x}%;
                  bottom: -10px;
                  font-size: ${p.size}px;
                  animation: ${particleFloat} ${p.duration}s ${p.delay}s ease-out both;
                `}
              >
                {p.emoji}
              </span>
            ))}
          </div>
        </>
      )}

      <div css={overlayStyle} onClick={confirming ? undefined : onClose}>
        <div css={modalStyle} onClick={(e) => e.stopPropagation()}>
          <div css={handleStyle} />
          <h2 css={modalTitleStyle}>✨ 프레스티지 (환생)</h2>
          <p css={modalSubtitleStyle}>
            환생 시 진행이 초기화되고 영구 보너스를 획득합니다
          </p>

          {/* 초기화 항목 */}
          <div css={sectionLabelStyle}>초기화될 항목</div>
          <div css={resetListStyle}>
            <div css={resetItemStyle}>⚠️ 원소 인벤토리 → 초기값 (4종 각 5개)</div>
            <div css={resetItemStyle}>⚠️ 골드 → 0 (스타터 골드로 교체)</div>
            <div css={resetItemStyle}>⚠️ 강화 레벨 → 모두 0으로 리셋</div>
            <div css={resetItemStyle}>⚠️ 상점 버프 → 초기화</div>
          </div>

          {/* 획득할 프레스티지 보너스 */}
          <div css={sectionLabelStyle}>획득할 영구 보너스 ({nextEntry.count}회차)</div>
          <div css={bonusCardStyle}>
            <div css={bonusRowStyle}>
              <span css={bonusLabelStyle}>💰 골드 수입 배율</span>
              <span css={bonusValueStyle}>×{nextEntry.goldMultiplier}</span>
            </div>
            <div css={bonusRowStyle}>
              <span css={bonusLabelStyle}>⚡ 원소 스폰 배율</span>
              <span css={bonusValueStyle}>×{nextEntry.spawnMultiplier}</span>
            </div>
            <div css={bonusRowStyle}>
              <span css={bonusLabelStyle}>🪙 스타터 골드</span>
              <span css={bonusValueStyle}>{nextEntry.starterGold.toLocaleString()}G</span>
            </div>
          </div>

          {/* 칭호 잠금해제 미리보기 */}
          <div css={sectionLabelStyle}>잠금해제될 칭호</div>
          <div css={titlePreviewStyle}>
            <span css={titleEmojiStyle}>{nextEntry.titleEmoji}</span>
            <div>
              <div css={titleTextStyle}>{nextEntry.title}</div>
              <div css={titleSubStyle}>{nextEntry.count}회 환생 달성 칭호</div>
            </div>
          </div>

          {/* 버튼 */}
          <div css={buttonRowStyle}>
            <button
              css={cancelButtonStyle}
              onClick={onClose}
              disabled={confirming}
            >
              취소
            </button>
            <button
              css={confirmButtonStyle(!canConfirm || confirming)}
              onClick={handleConfirm}
              disabled={!canConfirm || confirming}
            >
              {confirming ? '환생 중...' : '환생하기 ✨'}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
