"use client"; import React, { useState, useEffect, useCallback, useRef } from "react"; import FormPage from './FormPage'; import { CardData } from "../exportType/types"; import SwipeCards from "../components/Cards"; import { ChatSetting } from "../exportType/types"; import { FormData, PROFICIENCY_LEVELS } from './formTypes'; // --- Helper function to get default form data --- const getDefaultFormData = (): FormData => ({ Hackathon: '', mainTheme: '', tracksStack: [''], students: [{ studentName: '', skills: [{ skillName: '', proficiency: PROFICIENCY_LEVELS[1] }] }], }); // --- New Initializer Function --- const getInitialState = () => { if (typeof window === 'undefined') { return { data: getDefaultFormData(), showForm: true, runEffect: false }; } const storedFormData = localStorage.getItem('formData'); if (storedFormData) { localStorage.removeItem('formData'); return { data: JSON.parse(storedFormData) as FormData, showForm: false, runEffect: true, }; } return { data: getDefaultFormData(), showForm: true, runEffect: false }; }; export default function Home() { const [ideaResponse, setIdeaResponse] = useState(""); const [generatedCards, setGeneratedCards] = useState([]); // New state for parsed cards const [initialState] = useState(getInitialState); const [showForm, setShowForm] = useState(initialState.showForm); const initialIdeaGenerationAttempted = useRef(false); const [settings] = useState({ temperature: 1, model: "gemini-2.5-flash-lite", systemInstruction: `You are an elite hackathon idea generator. Your task is to choose at lease two track and generate five different creative, feasible, and relevant project idea. The output MUST be in Markdown format and strictly follow this structure: ### Project Idea Title **Track** [print out the track you used] **Concept:** [A concise, single paragraph description of the product and its primary function.]`, }); const generateIdeas = useCallback(async (dataToProcess: FormData) => { const parseAiResponse = (markdownString: string): CardData[] => { console.log("Raw AI Response:", markdownString); const ideas: CardData[] = []; const ideaBlocks = markdownString.split("### ").filter(block => block.trim() !== ""); ideaBlocks.forEach((block, index) => { const titleMatch = block.match(/^(.*?)(?=\n\*\*Track\*\*|$)/s); const trackMatch = block.match(/\*\*Track\*\*\s*:\s*(.*?)(?=\n\*\*Concept\*\*|$)/s); const conceptMatch = block.match(/\*\*Concept:\*\*\s*(.*)/s); const title = titleMatch ? titleMatch[1].trim() : `Idea ${index + 1}`; const summary = conceptMatch ? conceptMatch[1].trim() : "No concept provided."; const tracksRaw = trackMatch ? trackMatch[1].trim() : ""; const tracks = tracksRaw.split(',').map(track => track.trim()).filter(track => track !== ''); ideas.push({ id: index + 1, title, tracks, summary, }); }); console.log("Parsed Cards:", ideas); return ideas; }; const submissionData: FormData = { ...dataToProcess, tracksStack: dataToProcess.tracksStack.filter(tracks => tracks.trim() !== ''), students: dataToProcess.students .map(student => ({ ...student, skills: student.skills.filter(skill => skill.skillName.trim() !== ''), })) .filter(student => student.studentName.trim() !== '' || student.skills.length > 0), }; const prompt = ` Hackathon: ${submissionData.Hackathon} Main Theme: ${submissionData.mainTheme} Required Tracks Stack: ${submissionData.tracksStack.join(', ')} Team Members and Skills: ${submissionData.students.map(s => `${s.studentName || 'Unamed Member'} (Skills: ${s.skills.map(sk => `${sk.skillName} - ${sk.proficiency}`).join(', ')})` ).join('; ')} Using the SYSTEM INSTRUCTIONS, generate 5 project ideas based on the data above.`; try { setIdeaResponse("Generating ideas... Please wait."); setGeneratedCards([]); const response = await fetch("/api/generate-idea", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ prompt: prompt, settings: settings, }), }); const data = await response.json(); if (data.error || !response.ok) { console.error("AI Error:", data.error); setIdeaResponse(`Error: Failed to generate idea. ${data.error || response.statusText}`); return; } setIdeaResponse(data.response); const parsedCards = parseAiResponse(data.response); setGeneratedCards(parsedCards); } catch (error) { console.error("Request Failed:", error); let errorMessage = "An unknown error occurred."; if (error instanceof Error) { errorMessage = error.message; } else if (typeof error === 'string') { errorMessage = error; } setIdeaResponse(`A network error occurred. Please try again. Details: ${errorMessage}`); } }, [settings]); useEffect(() => { if (initialState.runEffect && !initialIdeaGenerationAttempted.current) { // eslint-disable-next-line react-hooks/set-state-in-effect generateIdeas(initialState.data); initialIdeaGenerationAttempted.current = true; } }, [initialState, generateIdeas]); const handleFormSubmitFromFormPage = (submittedData: FormData) => { setShowForm(false); generateIdeas(submittedData); }; // --- JSX Rendering --- return (
{showForm ? ( ) : ( <> {generatedCards.length > 0 ? ( ) : ( <>

Generated Project Idea 💡

Generated Ideas:

') }} /> {ideaResponse === "" &&

Submit the form to generate project ideas.

}
)} )}
); }