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 = () => (
{view === 'savings' ? '최적의 저축액을 계산 중...' : '냉장고 속 재료로 맛있는 레시피 생성 중...'}
티끌 모아 태산!
작은 소비를 막는 것이 짠테크의 시작입니다. 오늘 아낀 커피값 4,500원을 저축해볼까요?
얼마까지 저축할 의향이 있나요?
{savingsResult?.toLocaleString()}원
지금 바로 저축하세요!
"커피 한 잔 대신 파킹통장으로 이체하고
자산을 불리는 습관을 만들어보세요!"
냉장고 속 재료들을 입력해주시면
최고의 짠테크 식단을 짜드릴게요.
입력된 식재료가 없습니다.
하나 이상의 재료를 추가해주세요!
{mealResult.reason}