import { css, keyframes } from '@emotion/react';
import { useCallback, useEffect, useState } from 'react';
import { BottomTabBar } from './components/BottomTabBar';
import { OfflineRewardModal } from './components/OfflineRewardModal';
import { AchievementToast } from './components/AchievementToast';
import { AdBanner } from './components/AdBanner';
import { IntroSplash } from './components/IntroSplash';
import { ElementsScreen } from './components/screens/ElementsScreen';
import { EvolutionScreen } from './components/screens/EvolutionScreen';
import { FusionScreen } from './components/screens/FusionScreen';
import { ShopScreen } from './components/screens/ShopScreen';
import { AchievementsScreen } from './components/screens/AchievementsScreen';
import { SettingsScreen } from './components/screens/SettingsScreen';
import { TutorialOverlay } from './components/tutorial/TutorialOverlay';
import { useIdleTick } from './hooks/useIdleTick';
import { useGameStore } from './store/useGameStore';
import { trackGameEvent } from './platform/analytics';
import { useTimeOfDay, getPalette } from './lib/timeOfDay';

const legendaryShake = keyframes`
  0%, 100% { transform: translate3d(0, 0, 0); filter: none; }
  15% { transform: translate3d(-6px, 2px, 0); filter: drop-shadow(0 0 18px rgba(255, 215, 0, 0.7)); }
  30% { transform: translate3d(5px, -3px, 0); }
  45% { transform: translate3d(-4px, -2px, 0); }
  60% { transform: translate3d(4px, 3px, 0); }
  75% { transform: translate3d(-2px, 1px, 0); }
`;

const rootStyle = (shaking: boolean, background: string) => css`
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: ${background};
  overflow: hidden;
  font-family:
    'Pretendard',
    -apple-system,
    BlinkMacSystemFont,
    sans-serif;
  animation: ${shaking ? css`${legendaryShake} 0.42s ease-out` : 'none'};
  transition: background-color 1.5s ease-in-out;
`;

const contentStyle = css`
  flex: 1;
  overflow-y: auto;
  padding-bottom: 106px;
`;

export function App() {
  const { activeTab, setActiveTab, elements, gold, elementLevels } = useGameStore();
  const [shaking, setShaking] = useState(false);
  const [showIntro, setShowIntro] = useState(() => localStorage.getItem('firstspark-intro-seen') !== '1');
  useIdleTick();
  const timeOfDay = useTimeOfDay();
  const palette = getPalette(timeOfDay);

  const handleIntroDone = useCallback(() => {
    localStorage.setItem('firstspark-intro-seen', '1');
    setShowIntro(false);
  }, []);

  useEffect(() => {
    const ownedCount = Object.values(elements).filter((c) => c > 0).length;
    const totalLevel = Object.values(elementLevels).reduce((sum, lv) => sum + lv, 0);
    trackGameEvent('app_open', {
      platform: 'web',
      platform_time: new Date().toISOString(),
      owned_element_count: ownedCount,
      gold,
      total_enhance_level: totalLevel,
    });
  }, []);

  useEffect(() => {
    const handler = () => {
      setShaking(true);
      window.setTimeout(() => setShaking(false), 440);
    };
    window.addEventListener('legendaryImpact', handler);
    return () => window.removeEventListener('legendaryImpact', handler);
  }, []);

  return (
    <div css={rootStyle(shaking, palette.background)}>
      {showIntro && (
        <IntroSplash
          onDone={handleIntroDone}
        />
      )}
      <OfflineRewardModal />
      <AchievementToast />
      <div css={contentStyle}>
        {activeTab === 'elements' && <ElementsScreen />}
        {activeTab === 'evolution' && <EvolutionScreen />}
        {activeTab === 'fusion' && <FusionScreen />}
        {activeTab === 'shop' && <ShopScreen />}
        {activeTab === 'achievements' && <AchievementsScreen />}
        {activeTab === 'settings' && <SettingsScreen />}
      </div>
      <AdBanner />
      <BottomTabBar activeTab={activeTab} onTabChange={setActiveTab} />
      <TutorialOverlay />
    </div>
  );
}
