import React, { useState } from ‘react’;

// Main App component
function App() {
const [ingredients, setIngredients] = useState(”); // State to store user’s ingredient input
const [recipes, setRecipes] = useState(”); // State to store generated recipe ideas
const [isLoading, setIsLoading] = useState(false); // State to manage loading indicator
const [error, setError] = useState(”); // State to store any error messages

// Function to handle changes in the input textarea
const handleInputChange = (event) => {
setIngredients(event.target.value);
setError(”); // Clear error when user starts typing again
};

// Function to call the Gemini API and generate recipes
const generateRecipes = async () => {
if (!ingredients.trim()) {
setError(‘Please enter some ingredients to get recipe ideas.’);
return;
}

setIsLoading(true); // Set loading to true
setError(”); // Clear previous errors
setRecipes(”); // Clear previous recipes

const prompt = `Suggest 3-5 recipe ideas based on the following ingredients. For each recipe, provide a brief description and a few key steps.
Ingredients: ${ingredients}
`;

// Prepare the payload for the Gemini API call
const chatHistory = [];
chatHistory.push({ role: “user”, parts: [{ text: prompt }] });
const payload = { contents: chatHistory };

// API key is left empty as Canvas will provide it at runtime
const apiKey = “”;
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;

try {
// Make the fetch call to the Gemini API
const response = await fetch(apiUrl, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify(payload)
});

// Check if the response was successful
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API error: ${response.status} ${response.statusText} – ${errorData.error.message || ‘Unknown error’}`);
}

const result = await response.json();

// Check for valid response structure
if (result.candidates && result.candidates.length > 0 &&
result.candidates[0].content && result.candidates[0].content.parts &&
result.candidates[0].content.parts.length > 0) {
const text = result.candidates[0].content.parts[0].text;
setRecipes(text); // Set the generated recipes
} else {
setError(‘Could not generate recipes. Please try again or rephrase your ingredients.’);
console.error(‘Unexpected API response structure:’, result);
}
} catch (err) {
console.error(‘Error generating recipes:’, err);
setError(`Failed to generate recipes: ${err.message}. Please check your input and try again.`);
} finally {
setIsLoading(false); // Set loading to false regardless of success or failure
}
};

return (

Recipe Idea Generator

{/* Input section */}


{/* Action button */}

{/* Error message display */}
{error && (

Error:
{error}

)}

{/* Recipe display section */}
{recipes && (

Your Recipe Ideas:

{/* Display recipes, handling newlines for formatting */}
{recipes.split(‘\n’).map((line, index) => (

{line}

))}

)}

);
}

export default App;