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 elementsData from '../../data/elements.json';

const BOOST_DURATION_SEC = 30;

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 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: 'fusion_scroll',
    name: '합성 두루마리',
    desc: '랜덤 원소 합성 시도',
    icon: '📜',
    price: 80,
    rarity: 'rare',
  },
  {
    id: 'gold_bag',
    name: '골드 주머니',
    desc: '+50 골드 즉시 획득',
    icon: '👝',
    price: 100,
    rarity: 'epic',
  },
];

export function ShopScreen() {
  const { gold, addGold, addElement, activeBoosts, activateBoost } = useGameStore();
  const [boughtId, setBoughtId] = useState<string | null>(null);
  const [noGoldId, setNoGoldId] = 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 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(50);
    } else if (item.id === 'fusion_scroll') {
      // 미보유 원소 우선 제공, 없으면 보유 중 랜덤
      const currentElements = useGameStore.getState().elements;
      const unlockedIds = elementsData
        .filter((el) => isElementUnlocked(el.id, currentElements))
        .map((el) => el.id);
      const unownedIds = unlockedIds.filter((id) => (currentElements[id] ?? 0) === 0);
      const pool = unownedIds.length > 0 ? unownedIds : unlockedIds;
      if (pool.length > 0) {
        addElement(pool[Math.floor(Math.random() * pool.length)]);
      }
    } else if (item.id === 'fire_boost' || item.id === 'water_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>
      <div css={shopGridStyle}>
        {SHOP_ITEMS.map((item) => {
          const remaining = getRemainingSeconds(item.id);
          const isActive = remaining > 0;
          const progress = (remaining / BOOST_DURATION_SEC) * 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>
  );
}
