import { useState, useEffect, useCallback } from 'react'; import { resetAllData } from '@/contexts/budget/storageUtils'; import { resetAllStorageData } from '@/utils/storageUtils'; export const useDataInitialization = (resetBudgetData?: () => void) => { const [isInitialized, setIsInitialized] = useState(false); // 모든 데이터 초기화 함수 const initializeAllData = useCallback(() => { console.log('모든 데이터 초기화 시작'); // 현재 dontShowWelcome 값 백업 const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome'); console.log('useDataInitialization - 초기화 전 dontShowWelcome 값:', dontShowWelcomeValue); // 여러번 초기화 실행 for (let i = 0; i < 3; i++) { // 모든 데이터 완전히 삭제 및 초기화 resetAllData(); resetAllStorageData(); // localStorage 직접 초기화 (추가 보호) clearAllAnalyticsData(); } // 컨텍스트 데이터 리셋 (마지막에 한번 더) if (resetBudgetData) { resetBudgetData(); } // 초기화 후 dontShowWelcome 값 확인 const afterResetValue = localStorage.getItem('dontShowWelcome'); console.log('useDataInitialization - 초기화 후 dontShowWelcome 값:', afterResetValue); // 값이 유지되지 않았다면 복원 if (dontShowWelcomeValue && afterResetValue !== dontShowWelcomeValue) { console.log('useDataInitialization - dontShowWelcome 값 복원:', dontShowWelcomeValue); localStorage.setItem('dontShowWelcome', dontShowWelcomeValue); } console.log('모든 데이터 초기화 완료'); return true; }, [resetBudgetData]); // 분석 페이지 데이터 초기화 함수 const clearAllAnalyticsData = useCallback(() => { // 분석 관련 데이터 강제 삭제 const analyticsKeys = [ 'analytics', 'monthlyTotals', 'chartData', 'expenseHistory', 'budgetHistory', 'categorySpending', 'monthlyData', 'expenseData', 'analyticData' ]; analyticsKeys.forEach(key => { localStorage.removeItem(key); }); // 모든 localStorage 순회하며 월간, 차트, 분석 관련 키워드 삭제 for (let i = localStorage.length - 1; i >= 0; i--) { const key = localStorage.key(i); if (key && ( key.includes('month') || key.includes('chart') || key.includes('analytics') || key.includes('expense') || key.includes('budget') || key.includes('total') )) { console.log(`분석 데이터 삭제: ${key}`); localStorage.removeItem(key); } } return true; }, []); // 데이터 초기화 실행 useEffect(() => { if (!isInitialized) { const result = initializeAllData(); setIsInitialized(result); } // 방문 기록 저장 (초기화 후에 저장) localStorage.setItem('hasVisitedBefore', 'true'); }, [isInitialized, initializeAllData]); return { isInitialized, initializeAllData, clearAllAnalyticsData }; };