
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { useState, useEffect } from "react";
import Index from "./pages/Index";
import Transactions from "./pages/Transactions";
import Analytics from "./pages/Analytics";
import Settings from "./pages/Settings";
import ProfileManagement from "./pages/ProfileManagement";
import NotificationSettings from "./pages/NotificationSettings";
import SecurityPrivacySettings from "./pages/SecurityPrivacySettings";
import HelpSupport from "./pages/HelpSupport";
import PaymentMethods from "./pages/PaymentMethods";
import NotFound from "./pages/NotFound";
import Login from "./pages/Login";
import Register from "./pages/Register";
import ForgotPassword from "./pages/ForgotPassword";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
});

const App = () => {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    // 애플리케이션 초기화 및 로딩 상태 관리
    try {
      // 기본 예산 데이터 초기화
      if (!localStorage.getItem('budgetData')) {
        const defaultBudgetData = {
          daily: {
            targetAmount: 40000,
            spentAmount: 0,
            remainingAmount: 40000
          },
          weekly: {
            targetAmount: 280000,
            spentAmount: 0,
            remainingAmount: 280000
          },
          monthly: {
            targetAmount: 1200000,
            spentAmount: 0,
            remainingAmount: 1200000
          }
        };
        localStorage.setItem('budgetData', JSON.stringify(defaultBudgetData));
      }
      
      // 기본 카테고리 예산 설정
      if (!localStorage.getItem('categoryBudgets')) {
        const defaultCategoryBudgets = {
          식비: 400000,
          생활비: 600000,
          교통비: 200000
        };
        localStorage.setItem('categoryBudgets', JSON.stringify(defaultCategoryBudgets));
      }
      
      // 빈 트랜잭션 배열 초기화
      if (!localStorage.getItem('transactions')) {
        localStorage.setItem('transactions', JSON.stringify([]));
      }
      
      setIsLoaded(true);
    } catch (error) {
      console.error('앱 초기화 중 오류 발생:', error);
      // 오류가 발생해도 앱 로딩
      setIsLoaded(true);
    }
  }, []);

  if (!isLoaded) {
    return <div className="flex items-center justify-center h-screen">
      <div className="text-center">
        <div className="animate-spin h-8 w-8 border-4 border-neuro-income border-t-transparent rounded-full mx-auto mb-4"></div>
        <p className="text-gray-600">앱을 로딩 중입니다...</p>
      </div>
    </div>;
  }

  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <Toaster />
        <Sonner />
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Index />} />
            <Route path="/transactions" element={<Transactions />} />
            <Route path="/analytics" element={<Analytics />} />
            <Route path="/settings" element={<Settings />} />
            <Route path="/profile-management" element={<ProfileManagement />} />
            <Route path="/notification-settings" element={<NotificationSettings />} />
            <Route path="/security-privacy-settings" element={<SecurityPrivacySettings />} />
            <Route path="/help-support" element={<HelpSupport />} />
            <Route path="/payment-methods" element={<PaymentMethods />} />
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/forgot-password" element={<ForgotPassword />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </BrowserRouter>
      </TooltipProvider>
    </QueryClientProvider>
  );
};

export default App;
