import { useEffect, useState } from 'react';
import Header from './components/Header';
import ClickArea from './components/ClickArea';
import UpgradeShop from './components/UpgradeShop';
import PrestigePanel from './components/PrestigePanel';
import { GameState } from './types';
import { initialUpgrades, initialPrestigeUpgrades } from './data/gameData';
import { formatNumber } from './utils/formatters';
import { saveGame, loadGame } from './utils/storage';
import './App.css';

function App() {
  const [gameState, setGameState] = useState<GameState>({
    currency: 0,
    totalCurrency: 0,
    clickValue: 1,
    passiveIncome: 0,
    autoClickRate: 0,
    prestigePoints: 0,
    prestigeMultiplier: 1,
    lastSaveTime: Date.now(),
    upgrades: initialUpgrades,
    prestigeUpgrades: initialPrestigeUpgrades
  });

  // Load saved game on startup
  useEffect(() => {
    const savedGame = loadGame();
    if (savedGame) {
      // Calculate offline progress
      const currentTime = Date.now();
      const timeDiff = (currentTime - savedGame.lastSaveTime) / 1000; // in seconds
      const offlineEarnings = Math.floor(savedGame.passiveIncome * timeDiff);
      
      if (offlineEarnings > 0) {
        savedGame.currency += offlineEarnings;
        savedGame.totalCurrency += offlineEarnings;
        alert(`Welcome back! You earned ${formatNumber(offlineEarnings)} while away.`);
      }
      
      savedGame.lastSaveTime = currentTime;
      setGameState(savedGame);
    }
  }, []);

  // Save game periodically
  useEffect(() => {
    const saveInterval = setInterval(() => {
      saveGame({...gameState, lastSaveTime: Date.now()});
    }, 10000); // Save every 10 seconds
    
    return () => clearInterval(saveInterval);
  }, [gameState]);

  // Passive income logic
  useEffect(() => {
    const incomeInterval = setInterval(() => {
      if (gameState.passiveIncome > 0) {
        setGameState(prev => ({
          ...prev,
          currency: prev.currency + prev.passiveIncome,
          totalCurrency: prev.totalCurrency + prev.passiveIncome
        }));
      }
    }, 1000); // Every second
    
    return () => clearInterval(incomeInterval);
  }, [gameState.passiveIncome]);

  // Auto click logic
  useEffect(() => {
    if (gameState.autoClickRate <= 0) return;
    
    const clickInterval = setInterval(() => {
      handleCurrencyClick();
    }, 1000 / gameState.autoClickRate);
    
    return () => clearInterval(clickInterval);
  }, [gameState.autoClickRate, gameState.clickValue]);

  const handleCurrencyClick = () => {
    const value = gameState.clickValue * gameState.prestigeMultiplier;
    setGameState(prev => ({
      ...prev,
      currency: prev.currency + value,
      totalCurrency: prev.totalCurrency + value
    }));
  };

  const purchaseUpgrade = (upgradeId: string) => {
    const upgrade = gameState.upgrades.find(u => u.id === upgradeId);
    if (!upgrade || gameState.currency < upgrade.cost) return;

    const updatedUpgrades = gameState.upgrades.map(u => {
      if (u.id === upgradeId) {
        const newLevel = u.level + 1;
        const newCost = Math.floor(u.baseCost * Math.pow(u.costMultiplier, newLevel));
        
        return { ...u, level: newLevel, cost: newCost };
      }
      return u;
    });

    let newClickValue = gameState.clickValue;
    let newPassiveIncome = gameState.passiveIncome;
    let newAutoClickRate = gameState.autoClickRate;

    switch (upgrade.type) {
      case 'clickValue':
        newClickValue += upgrade.value;
        break;
      case 'passive':
        newPassiveIncome += upgrade.value;
        break;
      case 'autoClick':
        newAutoClickRate += upgrade.value;
        break;
    }

    setGameState(prev => ({
      ...prev,
      currency: prev.currency - upgrade.cost,
      clickValue: newClickValue,
      passiveIncome: newPassiveIncome,
      autoClickRate: newAutoClickRate,
      upgrades: updatedUpgrades
    }));
  };

  const purchasePrestigeUpgrade = (upgradeId: string) => {
    const upgrade = gameState.prestigeUpgrades.find(u => u.id === upgradeId);
    if (!upgrade || gameState.prestigePoints < upgrade.cost || upgrade.purchased) return;

    const updatedUpgrades = gameState.prestigeUpgrades.map(u => {
      if (u.id === upgradeId) {
        return { ...u, purchased: true };
      }
      return u;
    });

    let newPrestigeMultiplier = gameState.prestigeMultiplier;
    newPrestigeMultiplier += upgrade.multiplierBonus;

    setGameState(prev => ({
      ...prev,
      prestigePoints: prev.prestigePoints - upgrade.cost,
      prestigeMultiplier: newPrestigeMultiplier,
      prestigeUpgrades: updatedUpgrades
    }));
  };

  const performPrestige = () => {
    // Calculate prestige points based on total currency earned
    const newPrestigePoints = Math.floor(Math.sqrt(gameState.totalCurrency / 1000000));
    
    if (newPrestigePoints <= 0) {
      alert("You need to earn more currency before prestiging!");
      return;
    }

    if (!window.confirm(`Are you sure you want to prestige? You'll earn ${newPrestigePoints} prestige points but will lose all progress except prestige upgrades.`)) {
      return;
    }

    // Reset game but keep prestige upgrades and add prestige points
    setGameState(prev => ({
      ...prev,
      currency: 0,
      totalCurrency: 0,
      clickValue: 1,
      passiveIncome: 0,
      autoClickRate: 0,
      prestigePoints: prev.prestigePoints + newPrestigePoints,
      lastSaveTime: Date.now(),
      upgrades: initialUpgrades
      // Note: prestigeUpgrades and prestigeMultiplier are kept
    }));
  };

  return (
    <div className="app-container">
      <Header 
        currency={gameState.currency} 
        clickValue={gameState.clickValue * gameState.prestigeMultiplier}
        passiveIncome={gameState.passiveIncome}
        autoClickRate={gameState.autoClickRate}
        prestigePoints={gameState.prestigePoints}
        prestigeMultiplier={gameState.prestigeMultiplier}
      />
      
      <main>
        <ClickArea onCurrencyClick={handleCurrencyClick} />
        
        <div className="game-sections">
          <UpgradeShop 
            upgrades={gameState.upgrades} 
            currency={gameState.currency}
            onPurchase={purchaseUpgrade}
            prestigeMultiplier={gameState.prestigeMultiplier}
          />
          
          <PrestigePanel
            totalCurrency={gameState.totalCurrency}
            prestigePoints={gameState.prestigePoints}
            prestigeUpgrades={gameState.prestigeUpgrades}
            onPrestige={performPrestige}
            onPurchaseUpgrade={purchasePrestigeUpgrade}
          />
        </div>
      </main>
    </div>
  );
}

export default App;
