import { css, keyframes } from '@emotion/react';
import { useState, useEffect } from 'react';
import { adaptive } from '../../styles/adaptive';
import { rarityGradient } from '../../styles/gameColors';
import { useGameStore, isElementUnlocked } from '../../store/useGameStore';
import { trackGameEvent } from '../../platform/analytics';
import { showRewardedAd } from '../../platform/ads';
import elementsData from '../../data/elements.json';
import recipesData from '../../data/recipes.json';

const BOOST_DURATION_SEC = 30;
const ADVANCED_BOOST_DURATION_SEC = 45;

const containerStyle = css`
  padding: 24px 20px;
  background: ${adaptive.background};
  min-height: 100%;
`;

const titleStyle = css`
  font-size: 20px;
  font-weight: 700;
  color: ${adaptive.grey900};
  margin: 0 0 20px;
`;

const goldRowStyle = css`
  display: flex;
  align-items: center;
  gap: 6px;
  background: linear-gradient(135deg, #fff8e1, #fff3cd);
  padding: 10px 16px;
  border-radius: 12px;
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: 600;
  color: #5a3200;
`;

const rewardSectionStyle = css`
  background: #101828;
  color: #ffffff;
  border-radius: 18px;
  padding: 16px;
  margin-bottom: 18px;
  box-shadow: 0 12px 26px rgba(15, 23, 42, 0.18);
`;

const rewardHeaderStyle = css`
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
`;

const rewardTitleStyle = css`
  font-size: 15px;
  font-weight: 900;
`;

const rewardLimitStyle = css`
  font-size: 11px;
  font-weight: 800;
  color: rgba(255, 255, 255, 0.58);
  white-space: nowrap;
`;

const rewardGridStyle = css`
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;

  @media (max-width: 520px) {
    grid-template-columns: 1fr;
  }
`;

const rewardCardStyle = css`
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 14px;
  padding: 12px;
`;

const rewardNameStyle = css`
  font-size: 13px;
  font-weight: 900;
  margin-bottom: 4px;
`;

const rewardDescStyle = css`
  font-size: 11px;
  line-height: 1.4;
  font-weight: 700;
  color: rgba(255, 255, 255, 0.64);
  margin-bottom: 10px;
`;

const rewardButtonStyle = (enabled: boolean) => css`
  width: 100%;
  border: none;
  border-radius: 10px;
  background: ${enabled ? '#ffffff' : 'rgba(255, 255, 255, 0.14)'};
  color: ${enabled ? '#101828' : 'rgba(255, 255, 255, 0.52)'};
  padding: 10px 12px;
  font-size: 12px;
  font-weight: 900;
  cursor: ${enabled ? 'pointer' : 'default'};
`;

const rewardResultStyle = css`
  margin-top: 10px;
  border-radius: 10px;
  background: rgba(34, 197, 94, 0.15);
  color: #bbf7d0;
  padding: 8px 10px;
  font-size: 11px;
  font-weight: 900;
`;

const shopGridStyle = css`
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const shopItemStyle = css`
  display: flex;
  align-items: center;
  gap: 16px;
  background: ${adaptive.background};
  border: 1px solid ${adaptive.grey200};
  border-radius: 16px;
  padding: 16px;
  transition: border-color 0.2s, box-shadow 0.2s;
`;

const activeBoostPulse = keyframes`
  0%   { box-shadow: 0 0 0 0 rgba(255, 180, 0, 0.4); }
  70%  { box-shadow: 0 0 0 8px rgba(255, 180, 0, 0); }
  100% { box-shadow: 0 0 0 0 rgba(255, 180, 0, 0); }
`;

const shopItemActiveStyle = css`
  display: flex;
  align-items: center;
  gap: 16px;
  background: linear-gradient(135deg, #fffde7, #fff9c4);
  border: 1.5px solid #ffc107;
  border-radius: 16px;
  padding: 16px;
  animation: ${activeBoostPulse} 2s infinite;
`;

const buyFlashAnim = keyframes`
  0%   { transform: scale(1); }
  40%  { transform: scale(0.92); }
  70%  { transform: scale(1.04); }
  100% { transform: scale(1); }
`;

const noGoldShake = keyframes`
  0%, 100% { transform: translateX(0); }
  20%      { transform: translateX(-6px); }
  40%      { transform: translateX(6px); }
  60%      { transform: translateX(-4px); }
  80%      { transform: translateX(4px); }
`;

const shopItemNoGoldStyle = css`
  display: flex;
  align-items: center;
  gap: 16px;
  background: ${adaptive.background};
  border: 1.5px solid #ef5350;
  border-radius: 16px;
  padding: 16px;
  animation: ${noGoldShake} 0.5s ease-out;
`;

const itemIconBoxStyle = (rarity: string) => css`
  width: 56px;
  height: 56px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  flex-shrink: 0;
  background: ${rarityGradient(rarity)};
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
`;

const itemInfoStyle = css`
  flex: 1;
`;

const itemNameStyle = css`
  font-size: 15px;
  font-weight: 600;
  color: ${adaptive.grey900};
  margin: 0 0 4px;
`;

const itemDescStyle = css`
  font-size: 12px;
  color: ${adaptive.grey500};
  margin: 0;
`;

const activeDescStyle = css`
  font-size: 12px;
  font-weight: 600;
  color: #b8860b;
  margin: 0;
`;

const timerBarContainerStyle = css`
  background: rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  height: 4px;
  margin-top: 6px;
  overflow: hidden;
`;

const timerBarStyle = (progress: number) => css`
  background: linear-gradient(90deg, #ffc107, #ff9800);
  height: 100%;
  width: ${progress}%;
  border-radius: 4px;
  transition: width 1s linear;
`;

const buyButtonStyle = (canBuy: boolean, justBought: boolean) => css`
  background: ${justBought ? '#4caf50' : canBuy ? adaptive.blue500 : adaptive.grey200};
  color: ${canBuy || justBought ? '#ffffff' : adaptive.grey500};
  border: none;
  border-radius: 10px;
  padding: 8px 14px;
  font-size: 13px;
  font-weight: 600;
  cursor: ${canBuy ? 'pointer' : 'not-allowed'};
  white-space: nowrap;
  flex-shrink: 0;
  transition: background 0.2s;
  animation: ${justBought ? css`${buyFlashAnim} 0.4s ease-out` : 'none'};
`;

const SHOP_ITEMS = [
  {
    id: 'fire_boost',
    name: '불꽃 강화석',
    desc: `불꽃 원소 획득량 2배 (${BOOST_DURATION_SEC}초)`,
    icon: '🔥',
    price: 50,
    rarity: 'uncommon',
  },
  {
    id: 'water_boost',
    name: '물방울 강화석',
    desc: `물방울 원소 획득량 2배 (${BOOST_DURATION_SEC}초)`,
    icon: '💧',
    price: 50,
    rarity: 'uncommon',
  },
  {
    id: 'wind_boost',
    name: '바람 강화석',
    desc: `바람 원소 획득량 2배 (${BOOST_DURATION_SEC}초)`,
    icon: '🌪️',
    price: 50,
    rarity: 'uncommon',
  },
  {
    id: 'earth_boost',
    name: '대지 강화석',
    desc: `흙 원소 획득량 2배 (${BOOST_DURATION_SEC}초)`,
    icon: '🌱',
    price: 50,
    rarity: 'uncommon',
  },
  {
    id: 'starter_bundle',
    name: '기본 원소 묶음',
    desc: 'Tier 1 원소를 각각 +3 획득',
    icon: '🧪',
    price: 90,
    rarity: 'uncommon',
  },
  {
    id: 'fusion_scroll',
    name: '합성 두루마리',
    desc: '현재 만들 수 있는 미발견 원소 1개 획득',
    icon: '📜',
    price: 160,
    rarity: 'rare',
  },
  {
    id: 'global_spawn_boost',
    name: '정령 가속 코어',
    desc: `전체 원소 생산량 2배 (${ADVANCED_BOOST_DURATION_SEC}초)`,
    icon: '⚙️',
    price: 180,
    rarity: 'rare',
  },
  {
    id: 'gold_boost',
    name: '황금 향로',
    desc: `골드 수입 2배 (${ADVANCED_BOOST_DURATION_SEC}초)`,
    icon: '🏺',
    price: 200,
    rarity: 'rare',
  },
  {
    id: 'tier_2_boost',
    name: '2티어 공명석',
    desc: `Tier 2 원소 생산량 2배 (${ADVANCED_BOOST_DURATION_SEC}초)`,
    icon: '🔷',
    price: 260,
    rarity: 'epic',
  },
  {
    id: 'tier_3_boost',
    name: '3티어 공명석',
    desc: `Tier 3 원소 생산량 2배 (${ADVANCED_BOOST_DURATION_SEC}초)`,
    icon: '💠',
    price: 520,
    rarity: 'epic',
  },
  {
    id: 'gold_bag',
    name: '골드 주머니',
    desc: '+120 골드 즉시 획득',
    icon: '👝',
    price: 90,
    rarity: 'epic',
  },
];

export function ShopScreen() {
  const {
    gold,
    addGold,
    addElement,
    activeBoosts,
    activateBoost,
    adRewardProgress,
    claimAdFreeBoost,
    claimAdDailyGacha,
  } = useGameStore();
  const [boughtId, setBoughtId] = useState<string | null>(null);
  const [noGoldId, setNoGoldId] = useState<string | null>(null);
  const [rewardLoadingId, setRewardLoadingId] = useState<string | null>(null);
  const [rewardResult, setRewardResult] = useState<string | null>(null);
  const [, setTick] = useState(0);

  // 버프 타이머 갱신 (1초마다 re-render)
  useEffect(() => {
    const interval = setInterval(() => setTick((t) => t + 1), 1000);
    return () => clearInterval(interval);
  }, []);

  const getRemainingSeconds = (boostId: string): number => {
    const expiresAt = activeBoosts[boostId];
    if (!expiresAt) return 0;
    return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000));
  };

  const handleAdFreeBoost = async () => {
    if (rewardLoadingId || adRewardProgress.freeBoostUses >= 3) return;
    setRewardLoadingId('free_boost');
    try {
      const result = await showRewardedAd();
      if (result.rewarded && claimAdFreeBoost()) {
        setRewardResult('전체 생산 x2 부스트 30분이 적용되었습니다.');
        trackGameEvent('rewarded_ad_claimed', {
          placement: 'shop_free_boost',
          reward: 'global_spawn_boost_30m',
        });
      }
    } finally {
      setRewardLoadingId(null);
    }
  };

  const handleAdDailyGacha = async () => {
    if (rewardLoadingId || adRewardProgress.dailyGachaClaimed) return;
    setRewardLoadingId('daily_gacha');
    try {
      const adResult = await showRewardedAd();
      if (adResult.rewarded) {
        const gachaResult = claimAdDailyGacha();
        if (gachaResult.success && gachaResult.elementId) {
          const el = elementsData.find((item) => item.id === gachaResult.elementId);
          setRewardResult(`${el?.emoji ?? '✨'} ${el?.name ?? gachaResult.elementId} 원소를 획득했습니다.`);
          trackGameEvent('rewarded_ad_claimed', {
            placement: 'shop_daily_gacha',
            reward: gachaResult.elementId,
          });
        }
      }
    } finally {
      setRewardLoadingId(null);
    }
  };

  const handleBuy = (item: (typeof SHOP_ITEMS)[0]) => {
    // 스토어에서 최신 골드 값을 직접 읽어 스테일 클로저로 인한 음수 골드 버그 방지
    const currentGold = useGameStore.getState().gold;
    if (currentGold < item.price) {
      setNoGoldId(item.id);
      setTimeout(() => setNoGoldId(null), 600);
      return;
    }
    addGold(-item.price);

    if (item.id === 'gold_bag') {
      addGold(120);
    } else if (item.id === 'starter_bundle') {
      addElement('fire', 3);
      addElement('water', 3);
      addElement('wind', 3);
      addElement('earth', 3);
    } else if (item.id === 'fusion_scroll') {
      // 현재 재료로 만들 수 있는 미발견 원소를 우선 제공
      const currentElements = useGameStore.getState().elements;
      const discoveredElements = useGameStore.getState().discoveredElements;
      const craftableIds = recipesData
        .filter(
          (recipe) =>
            !discoveredElements.includes(recipe.result) &&
            isElementUnlocked(recipe.result, currentElements)
        )
        .map((recipe) => recipe.result);
      const fallbackIds = elementsData
        .filter((el) => discoveredElements.includes(el.id))
        .map((el) => el.id);
      const pool = craftableIds.length > 0 ? craftableIds : fallbackIds;
      if (pool.length > 0) {
        addElement(pool[Math.floor(Math.random() * pool.length)]);
      }
    } else if (
      item.id === 'global_spawn_boost' ||
      item.id === 'gold_boost' ||
      item.id === 'tier_2_boost' ||
      item.id === 'tier_3_boost'
    ) {
      activateBoost(item.id, ADVANCED_BOOST_DURATION_SEC);
    } else if (
      item.id === 'fire_boost' ||
      item.id === 'water_boost' ||
      item.id === 'wind_boost' ||
      item.id === 'earth_boost'
    ) {
      activateBoost(item.id, BOOST_DURATION_SEC);
    }

    trackGameEvent('item_purchased', {
      item_id: item.id,
      item_name: item.name,
      price: item.price,
      rarity: item.rarity,
    });

    setBoughtId(item.id);
    setTimeout(() => setBoughtId(null), 600);
  };

  return (
    <div css={containerStyle}>
      <h1 css={titleStyle}>상점</h1>
      <div css={goldRowStyle}>
        <span>💰</span>
        <span>보유 골드: {gold.toLocaleString()}</span>
      </div>

      <section css={rewardSectionStyle}>
        <div css={rewardHeaderStyle}>
          <div css={rewardTitleStyle}>무료 보상</div>
          <div css={rewardLimitStyle}>
            부스트 {adRewardProgress.freeBoostUses}/3 · 가챠 {adRewardProgress.dailyGachaClaimed ? '완료' : '가능'}
          </div>
        </div>
        <div css={rewardGridStyle}>
          <div css={rewardCardStyle}>
            <div css={rewardNameStyle}>⚡ 30분 생산 부스트</div>
            <div css={rewardDescStyle}>
              광고를 보고 전체 자동 생산 속도를 30분 동안 2배로 올립니다.
            </div>
            <button
              css={rewardButtonStyle(!rewardLoadingId && adRewardProgress.freeBoostUses < 3)}
              onClick={handleAdFreeBoost}
              disabled={Boolean(rewardLoadingId) || adRewardProgress.freeBoostUses >= 3}
            >
              {rewardLoadingId === 'free_boost'
                ? '광고 확인 중...'
                : adRewardProgress.freeBoostUses >= 3
                  ? '오늘 한도 완료'
                  : '광고 보고 받기'}
            </button>
          </div>
          <div css={rewardCardStyle}>
            <div css={rewardNameStyle}>🎁 일일 원소 가챠</div>
            <div css={rewardDescStyle}>
              광고를 보고 만들 수 있는 미발견 원소 또는 상위 원소 1개를 획득합니다.
            </div>
            <button
              css={rewardButtonStyle(!rewardLoadingId && !adRewardProgress.dailyGachaClaimed)}
              onClick={handleAdDailyGacha}
              disabled={Boolean(rewardLoadingId) || adRewardProgress.dailyGachaClaimed}
            >
              {rewardLoadingId === 'daily_gacha'
                ? '광고 확인 중...'
                : adRewardProgress.dailyGachaClaimed
                  ? '오늘 수령 완료'
                  : '광고 보고 뽑기'}
            </button>
          </div>
        </div>
        {rewardResult && <div css={rewardResultStyle}>{rewardResult}</div>}
      </section>

      <div css={shopGridStyle}>
        {SHOP_ITEMS.map((item) => {
          const remaining = getRemainingSeconds(item.id);
          const isActive = remaining > 0;
          const duration =
            item.id === 'global_spawn_boost' ||
            item.id === 'gold_boost' ||
            item.id === 'tier_2_boost' ||
            item.id === 'tier_3_boost'
              ? ADVANCED_BOOST_DURATION_SEC
              : BOOST_DURATION_SEC;
          const progress = (remaining / duration) * 100;

          return (
            <div key={item.id} css={noGoldId === item.id ? shopItemNoGoldStyle : isActive ? shopItemActiveStyle : shopItemStyle}>
              <div css={itemIconBoxStyle(item.rarity)}>{item.icon}</div>
              <div css={itemInfoStyle}>
                <p css={itemNameStyle}>{item.name}</p>
                {isActive ? (
                  <>
                    <p css={activeDescStyle}>✨ 활성 중 — {remaining}초 남음</p>
                    <div css={timerBarContainerStyle}>
                      <div css={timerBarStyle(progress)} />
                    </div>
                  </>
                ) : (
                  <p css={itemDescStyle}>{item.desc}</p>
                )}
              </div>
              <button
                css={buyButtonStyle(gold >= item.price, boughtId === item.id)}
                onClick={() => handleBuy(item)}
                disabled={gold < item.price}
              >
                {boughtId === item.id ? '✓' : `${item.price}G`}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
