import React, { useState, useEffect, useRef } from 'react'; import { PiggyBank, Utensils, ArrowLeft, Settings, CheckCircle2, Plus, X, RefreshCw, TrendingDown, ChevronRight, Lightbulb, Search } from 'lucide-react'; const apiKey = ""; // API Key is provided at runtime const App = () => { const [view, setView] = useState('main'); // 'main', 'savings', 'meal', 'result' const [maxAmount, setMaxAmount] = useState(5000); const [savingsResult, setSavingsResult] = useState(null); const [ingredients, setIngredients] = useState([]); const [newIngredient, setNewIngredient] = useState(''); const [mealResult, setMealResult] = useState(null); const [isLoading, setIsLoading] = useState(false); const [loadingProgress, setLoadingProgress] = useState(0); // 로딩 애니메이션 시뮬레이션 (동그라미 물 채우기) const startLoading = (callback) => { setIsLoading(true); setLoadingProgress(0); const interval = setInterval(() => { setLoadingProgress((prev) => { if (prev >= 100) { clearInterval(interval); setTimeout(() => { setIsLoading(false); callback(); }, 500); return 100; } return prev + 5; }); }, 50); }; // 랜덤 저축 로직 const generateSavings = () => { startLoading(() => { const amount = Math.floor(Math.random() * (maxAmount - 500 + 1)) + 500; const formattedAmount = Math.floor(amount / 100) * 100; // 100원 단위 절사 setSavingsResult(formattedAmount); setView('savings-result'); }); }; // 식재료 기반 레시피 추천 (Gemini API) const getRecipeRecommendation = async () => { if (ingredients.length === 0) return; startLoading(async () => { const prompt = `사용자의 냉장고 식재료: ${ingredients.join(', ')}. 이 재료들(전부 사용할 필요 없음)로 만들 수 있는 간단한 짠테크 식단 메뉴 1개와 짧은 요리법을 추천해줘. 답변은 반드시 JSON 형식으로 해줘: { "menu": "메뉴이름", "recipe": "간단설명", "reason": "추천이유" }`; try { let retries = 0; const maxRetries = 5; let delay = 1000; while (retries < maxRetries) { const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }], generationConfig: { responseMimeType: "application/json" } }) }); if (response.ok) { const data = await response.json(); const resultText = data.candidates?.[0]?.content?.parts?.[0]?.text; setMealResult(JSON.parse(resultText)); setView('meal-result'); return; } retries++; await new Promise(res => setTimeout(res, delay)); delay *= 2; } } catch (error) { console.error("Error fetching recipe:", error); setMealResult({ menu: "간단 볶음밥", recipe: "재료를 다지고 밥과 함께 볶으세요.", reason: "네트워크 오류로 기본 메뉴를 추천해 드려요!" }); setView('meal-result'); } }); }; const addIngredient = () => { if (newIngredient.trim() && !ingredients.includes(newIngredient.trim())) { setIngredients([...ingredients, newIngredient.trim()]); setNewIngredient(''); } }; const removeIngredient = (target) => { setIngredients(ingredients.filter(i => i !== target)); }; // 공통 로딩 오버레이 컴포넌트 (동그라미 물 채우기 애니메이션) const LoadingOverlay = () => (
{/* 물결 애니메이션 효과 */}
{loadingProgress}%

{view === 'savings' ? '최적의 저축액을 계산 중...' : '냉장고 속 재료로 맛있는 레시피 생성 중...'}

); return (
{isLoading && } {/* 상단바 */}
{view !== 'main' ? ( ) : (
S
)}

Smart Saver

{/* 메인 화면 */} {view === 'main' && (

티끌 모아 태산!

오늘의
짠테크 챌린지

작은 소비를 막는 것이 짠테크의 시작입니다. 오늘 아낀 커피값 4,500원을 저축해볼까요?

)} {/* 랜덤 저축 설정 화면 */} {view === 'savings' && (

저축 한도 설정

얼마까지 저축할 의향이 있나요?

setMaxAmount(parseInt(e.target.value))} className="w-full h-3 bg-cyan-100 rounded-lg appearance-none cursor-pointer accent-cyan-500" />
500원 10,000원
Limit {maxAmount.toLocaleString()}원
)} {/* 저축 결과 화면 */} {view === 'savings-result' && (

오늘의 짠테크 미션

{savingsResult?.toLocaleString()}원

지금 바로 저축하세요!

"커피 한 잔 대신 파킹통장으로 이체하고
자산을 불리는 습관을 만들어보세요!"

)} {/* 무지출 식단 추천 화면 (식재료 입력 및 추천) */} {view === 'meal' && (

냉장고 정보 입력

냉장고 속 재료들을 입력해주시면
최고의 짠테크 식단을 짜드릴게요.

setNewIngredient(e.target.value)} placeholder="예: 계란, 토마토, 참치" className="w-full p-4 pl-12 bg-slate-50 border-2 border-transparent rounded-[1.5rem] focus:bg-white focus:border-mint-400 outline-none transition-all font-bold placeholder:text-slate-300" onKeyPress={(e) => e.key === 'Enter' && addIngredient()} />
{ingredients.map((item) => ( {item} ))} {ingredients.length === 0 && (

입력된 식재료가 없습니다.

하나 이상의 재료를 추가해주세요!

)}
)} {/* 식단 결과 화면 */} {view === 'meal-result' && mealResult && (
Today's Pick

{mealResult.menu}

{mealResult.reason}

간편 조리법 가이드

{mealResult.recipe}
)}
); }; export default App;