import React, { useState, useCallback, useEffect } from 'react'; import ImageUploader from '../components/ImageUploader'; import AnalysisDisplay from '../components/AnalysisDisplay'; import Spinner from '../components/Spinner'; import { SparklesIcon, AlertTriangleIcon } from '../components/icons'; import { analyzeBonsai, getProtectionProfile, isAIConfigured } from '../services/geminiService'; import type { BonsaiAnalysis, BonsaiTree, View } from '../types'; import { AppStatus } from '../types'; interface AiStewardViewProps { setActiveView: (view: View) => void; } const AiStewardView: React.FC = ({ setActiveView }) => { const [status, setStatus] = useState(AppStatus.IDLE); const [analysisResult, setAnalysisResult] = useState(null); const [error, setError] = useState(''); const [currentImage, setCurrentImage] = useState(''); const [currentLocation, setCurrentLocation] = useState(''); const [prefilledSpecies, setPrefilledSpecies] = useState(''); const aiConfigured = isAIConfigured(); useEffect(() => { const species = window.sessionStorage.getItem('prefilled-species'); if (species) { setPrefilledSpecies(species); window.sessionStorage.removeItem('prefilled-species'); } }, []); const handleAnalyze = useCallback(async (imageBase64: string, species: string, location: string) => { setStatus(AppStatus.ANALYZING); setError(''); setAnalysisResult(null); setCurrentImage(imageBase64); setCurrentLocation(location); try { const result = await analyzeBonsai(imageBase64, species, location); if (result) { setAnalysisResult(result); setStatus(AppStatus.SUCCESS); } else { throw new Error('Failed to get analysis. The AI may be busy, or there was an issue with the request. Please try again.'); } } catch (e: any) { setError(e.message); setStatus(AppStatus.ERROR); } }, []); const handleSaveToDiary = async () => { try { if (!analysisResult || !currentImage || !currentLocation) { alert("Cannot save. Analysis data is missing."); return; } const treeName = window.prompt("What would you like to name this tree in your garden?", analysisResult.species); if (!treeName) return; // User cancelled // Fetch the protection profile for the new tree const protectionProfileData = await getProtectionProfile(analysisResult.species); const newTree: BonsaiTree = { id: `tree-${Date.now()}`, name: treeName, species: analysisResult.species, acquiredDate: new Date().toISOString(), source: "AI Steward Analysis", location: currentLocation, initialPhoto: currentImage, logs: [], analysisHistory: [{ date: new Date().toISOString(), analysis: analysisResult }], protectionProfile: protectionProfileData ? { ...protectionProfileData, alertsEnabled: true } : undefined, }; const storageKey = `yuki-app-bonsai-diary-trees`; const existingTreesJSON = window.localStorage.getItem(storageKey); const existingTrees: BonsaiTree[] = existingTreesJSON ? JSON.parse(existingTreesJSON) : []; const updatedTrees = [...existingTrees, newTree]; window.localStorage.setItem(storageKey, JSON.stringify(updatedTrees)); window.localStorage.setItem('yuki-bonsai-diary-newly-added-tree-id', newTree.id); setActiveView('garden'); } catch (error) { console.error("Failed to save tree to garden:", error); alert("Could not save the tree to your garden. An unexpected error occurred. Please check browser permissions for storage and try again."); } }; const handleReset = () => { setStatus(AppStatus.IDLE); setAnalysisResult(null); setError(''); setCurrentImage(''); setCurrentLocation(''); setPrefilledSpecies(''); }; const renderContent = () => { switch (status) { case AppStatus.ANALYZING: return
; case AppStatus.SUCCESS: return analysisResult ? : null; case AppStatus.ERROR: return (

An Error Occurred

{error}

); case AppStatus.IDLE: default: return ( <> {!aiConfigured && (

AI Features Disabled

Please set your Gemini API key in the{' '} {' '}to enable this feature.

)} ); } }; return (

New Tree Analysis

Welcome a new tree to your collection. Get an instant, expert analysis from Yuki, our AI Bonsai Sensei.

{renderContent()}
); }; export default AiStewardView;