
import React, { useEffect } from 'react';
import NavBar from '@/components/NavBar';
import AddTransactionButton from '@/components/AddTransactionButton';
import Header from '@/components/Header';
import WelcomeDialog from '@/components/onboarding/WelcomeDialog';
import HomeContent from '@/components/home/HomeContent';
import { useBudget } from '@/contexts/BudgetContext';
import { useAuth } from '@/contexts/auth';
import { useWelcomeDialog } from '@/hooks/useWelcomeDialog';
import { useDataInitialization } from '@/hooks/useDataInitialization';
import { useIsMobile } from '@/hooks/use-mobile';

// 메인 컴포넌트
const Index = () => {
  const {
    transactions,
    budgetData,
    selectedTab,
    setSelectedTab,
    handleBudgetGoalUpdate,
    updateTransaction,
    getCategorySpending,
    resetBudgetData
  } = useBudget();

  const { user } = useAuth();
  const { showWelcome, checkWelcomeDialogState, handleCloseWelcome } = useWelcomeDialog();
  const { isInitialized } = useDataInitialization(resetBudgetData);
  const isMobile = useIsMobile();

  // 초기화 후 0.5초 후에 환영 메시지 표시 상태 확인
  useEffect(() => {
    if (isInitialized) {
      const timeoutId = setTimeout(checkWelcomeDialogState, 500);
      return () => clearTimeout(timeoutId);
    }
  }, [isInitialized, checkWelcomeDialogState]);

  // 페이지가 처음 로드될 때 데이터 로딩 확인
  useEffect(() => {
    // 데이터 로드 상태 확인
    console.log('Index 페이지 마운트, 현재 데이터 상태:');
    console.log('트랜잭션:', transactions.length);
    console.log('예산 데이터:', budgetData);
    
    // 수동으로 이벤트 발생시켜 데이터 갱신
    window.dispatchEvent(new Event('transactionUpdated'));
    window.dispatchEvent(new Event('budgetDataUpdated'));
    window.dispatchEvent(new Event('categoryBudgetsUpdated'));
  }, []);

  // 앱이 포커스를 얻었을 때 데이터를 새로고침
  useEffect(() => {
    const handleFocus = () => {
      console.log('창이 포커스를 얻음 - 데이터 새로고침');
      // 이벤트 발생시켜 데이터 새로고침
      window.dispatchEvent(new Event('storage'));
      window.dispatchEvent(new Event('transactionUpdated'));
      window.dispatchEvent(new Event('budgetDataUpdated'));
      window.dispatchEvent(new Event('categoryBudgetsUpdated'));
    };

    window.addEventListener('focus', handleFocus);
    return () => window.removeEventListener('focus', handleFocus);
  }, []);

  return (
    <div className="min-h-screen bg-neuro-background pb-24">
      <div className="max-w-md mx-auto px-6">
        <Header />

        <HomeContent 
          transactions={transactions}
          budgetData={budgetData}
          selectedTab={selectedTab}
          setSelectedTab={setSelectedTab}
          handleBudgetGoalUpdate={handleBudgetGoalUpdate}
          updateTransaction={updateTransaction}
          getCategorySpending={getCategorySpending}
        />
      </div>
      <AddTransactionButton />
      <NavBar />
      
      {/* 첫 사용자 안내 팝업 */}
      <WelcomeDialog open={showWelcome} onClose={handleCloseWelcome} />
    </div>
  );
};

export default Index;
