import { css, keyframes } from '@emotion/react';
import { useState } from 'react';
import elementsData from '../../data/elements.json';
import {
  calcEnhanceCost,
  calcEffectiveIdleRate,
  ENHANCE_MAX_LEVEL,
  useGameStore,
} from '../../store/useGameStore';
import { FloatingOverlay } from '../FloatingOverlay';
import { trackGameEvent } from '../../platform/analytics';
import { showRewardedAd } from '../../platform/ads';
import { useFloatingItems } from '../../hooks/useFloatingItems';

const containerStyle = css`
  padding: 20px;
`;

const headerStyle = css`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
`;

const titleStyle = css`
  font-size: 20px;
  font-weight: 700;
  color: #191919;
  margin: 0;
`;

const goldBadgeStyle = css`
  display: flex;
  align-items: center;
  gap: 4px;
  background: linear-gradient(135deg, #ffd700, #ffaa00);
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 700;
  color: #5a3200;
`;

const cardStyle = css`
  background: #ffffff;
  border: 1px solid #f0f0f0;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
`;

const flashAnim = keyframes`
  0%   { background: #e8f4ff; box-shadow: 0 0 0 3px #3182F6, 0 0 20px rgba(49,130,246,0.5); }
  50%  { box-shadow: 0 0 0 2px #6C4DE6, 0 0 30px rgba(108,77,230,0.4); }
  100% { background: #ffffff; box-shadow: none; }
`;

const cardFlashStyle = css`
  background: #ffffff;
  border: 1px solid #3182F6;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
  animation: ${flashAnim} 0.9s ease-out;
`;

const enhanceButtonWrapStyle = css`
  position: relative;
`;

const cardHeaderStyle = css`
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
`;

const elementIconStyle = css`
  font-size: 32px;
`;

const elementInfoStyle = css`
  flex: 1;
`;

const elementNameStyle = css`
  font-size: 16px;
  font-weight: 700;
  color: #191919;
  margin: 0 0 2px;
`;

const elementSubStyle = css`
  font-size: 12px;
  color: #8b8b8b;
`;

const levelBarContainerStyle = css`
  background: #f5f5f5;
  border-radius: 6px;
  height: 6px;
  overflow: hidden;
  margin-bottom: 6px;
`;

const levelBarStyle = (progress: number) => css`
  background: linear-gradient(90deg, #3182f6, #6c4de6);
  height: 100%;
  width: ${progress}%;
  border-radius: 6px;
  transition: width 0.3s;
`;

const levelInfoRowStyle = css`
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #8b8b8b;
  margin-bottom: 12px;
`;

const rateChipStyle = css`
  font-size: 12px;
  font-weight: 600;
  color: #3182f6;
  background: #eef4ff;
  border-radius: 8px;
  padding: 2px 8px;
`;

const enhanceButtonStyle = (canEnhance: boolean) => css`
  width: 100%;
  padding: 10px;
  background: ${canEnhance ? 'linear-gradient(135deg, #3182F6, #6C4DE6)' : '#f0f0f0'};
  color: ${canEnhance ? '#ffffff' : '#c0c0c0'};
  border: none;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  cursor: ${canEnhance ? 'pointer' : 'not-allowed'};
  transition: opacity 0.15s;
  &:active {
    opacity: 0.8;
  }
`;

const fundingButtonStyle = (enabled: boolean) => css`
  width: 100%;
  padding: 9px;
  margin-top: 8px;
  background: ${enabled ? '#101828' : '#f0f0f0'};
  color: ${enabled ? '#ffffff' : '#a0a0a0'};
  border: none;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 800;
  cursor: ${enabled ? 'pointer' : 'default'};
`;

const fundingLimitStyle = css`
  margin-top: 6px;
  font-size: 10px;
  font-weight: 700;
  color: #8b8b8b;
  text-align: center;
`;

const emptyStyle = css`
  text-align: center;
  padding: 60px 20px;
  color: #8b8b8b;
`;

const LEVEL_LABELS = ['기본', '강화 I', '강화 II', '강화 III', '강화 IV', '강화 V (최대)'];

export function EvolutionScreen() {
  const {
    gold,
    elements,
    elementLevels,
    enhance,
    adRewardProgress,
    claimAdGoldFunding,
  } = useGameStore();
  const [flashedId, setFlashedId] = useState<string | null>(null);
  const [fundingId, setFundingId] = useState<string | null>(null);
  const { items: floatItems, add: addFloat } = useFloatingItems(1000);

  const ownedElements = elementsData.filter((el) => (elements[el.id] ?? 0) > 0);

  const handleEnhance = (elementId: string, buttonEl?: HTMLButtonElement | null) => {
    const result = enhance(elementId);
    if (result.success) {
      setFlashedId(elementId);
      setTimeout(() => setFlashedId(null), 900);

      // 레벨업 플로팅 텍스트
      const rect = buttonEl?.getBoundingClientRect();
      const x = rect ? rect.left + rect.width / 2 - 30 : window.innerWidth / 2 - 30;
      const y = rect ? rect.top - 10 : window.innerHeight * 0.5;
      addFloat({
        text: `⬆️ Lv.${result.newLevel}`,
        x,
        y,
        color: '#3182F6',
        fontSize: 15,
      });

      const el = elementsData.find((e) => e.id === elementId);
      trackGameEvent('enhancement_completed', {
        element_id: elementId,
        element_name: el?.name ?? '',
        new_level: result.newLevel ?? 0,
        cost: result.cost ?? 0,
      });
      trackGameEvent('level_up', {
        level_id: elementId,
        level: result.newLevel ?? 0,
      });
    }
  };

  const handleGoldFunding = async (elementId: string, cost: number) => {
    if (fundingId || adRewardProgress.goldFundingUses >= 5) return;
    const missingGold = Math.max(0, cost - useGameStore.getState().gold);
    if (missingGold <= 0) return;

    setFundingId(elementId);
    try {
      const adResult = await showRewardedAd();
      if (adResult.rewarded && claimAdGoldFunding(missingGold)) {
        addFloat({
          text: `+${missingGold} 💰`,
          x: window.innerWidth / 2 - 28,
          y: window.innerHeight * 0.38,
          color: '#F7C12A',
          fontSize: 15,
        });
        trackGameEvent('rewarded_ad_claimed', {
          placement: 'enhance_gold_funding',
          reward_gold: missingGold,
          element_id: elementId,
        });
      }
    } finally {
      setFundingId(null);
    }
  };

  if (ownedElements.length === 0) {
    return (
      <div css={containerStyle}>
        <div css={headerStyle}>
          <h1 css={titleStyle}>강화</h1>
          <div css={goldBadgeStyle}>💰 {gold}</div>
        </div>
        <div css={emptyStyle}>
          <div css={css`font-size: 48px; margin-bottom: 12px;`}>⬆️</div>
          <p>원소 탭에서 원소를 먼저 수집하세요.</p>
        </div>
      </div>
    );
  }

  return (
    <div css={containerStyle}>
      <div css={headerStyle}>
        <h1 css={titleStyle}>강화</h1>
        <div css={goldBadgeStyle}>💰 {gold}</div>
      </div>

      {ownedElements.map((el, index) => {
        const level = elementLevels[el.id] ?? 0;
        const isMax = level >= ENHANCE_MAX_LEVEL;
        const cost = isMax ? 0 : calcEnhanceCost(level);
        const canEnhance = !isMax && gold >= cost;
        const effectiveRate = calcEffectiveIdleRate(el.id, level);
        const progress = (level / ENHANCE_MAX_LEVEL) * 100;

        return (
          <div key={el.id} css={flashedId === el.id ? cardFlashStyle : cardStyle}>
            <div css={cardHeaderStyle}>
              <span css={elementIconStyle}>{el.emoji}</span>
              <div css={elementInfoStyle}>
                <p css={elementNameStyle}>{el.name}</p>
                <p css={elementSubStyle}>{LEVEL_LABELS[level]}</p>
              </div>
              <span css={css`font-size: 13px; font-weight: 700; color: #3182F6;`}>
                Lv.{level}/{ENHANCE_MAX_LEVEL}
              </span>
            </div>

            <div css={levelBarContainerStyle}>
              <div css={levelBarStyle(progress)} />
            </div>

            <div css={levelInfoRowStyle}>
              <span>자동 수집 효율</span>
              <span css={rateChipStyle}>
                ×{effectiveRate.toFixed(1)}{level > 0 ? ` (+${((effectiveRate / el.idleIncomeRate - 1) * 100).toFixed(0)}%)` : ''}
              </span>
            </div>

            <div css={enhanceButtonWrapStyle}>
              <button
                css={enhanceButtonStyle(canEnhance)}
                onClick={(e) => handleEnhance(el.id, e.currentTarget)}
                disabled={!canEnhance}
                data-tutorial={index === 0 ? 'elements-enhance-button' : undefined}
              >
                {isMax
                  ? '✅ 최대 레벨 달성'
                  : canEnhance
                    ? `⬆️ 강화 (💰 ${cost} 골드)`
                    : gold < cost
                      ? `🔒 골드 부족 (${cost - gold}G 필요)`
                      : `🔒 강화 불가`}
              </button>
              {!isMax && !canEnhance && gold < cost && (
                <>
                  <button
                    css={fundingButtonStyle(!fundingId && adRewardProgress.goldFundingUses < 5)}
                    onClick={() => handleGoldFunding(el.id, cost)}
                    disabled={Boolean(fundingId) || adRewardProgress.goldFundingUses >= 5}
                  >
                    {fundingId === el.id
                      ? '광고 확인 중...'
                      : adRewardProgress.goldFundingUses >= 5
                        ? '오늘 보충 한도 완료'
                        : `광고 보고 ${cost - gold}G 보충`}
                  </button>
                  <div css={fundingLimitStyle}>
                    오늘 골드 보충 {adRewardProgress.goldFundingUses}/5
                  </div>
                </>
              )}
            </div>
          </div>
        );
      })}
      <FloatingOverlay items={floatItems} />
    </div>
  );
}
