import React, { useState, useEffect } from 'react'; import useProjectStore from '../../store/projectStore'; export default function BusinessQuestionsScreen() { const [businessQuestions, setBusinessQuestions] = useState([]); const [businessAnswers, setBusinessAnswers] = useState({}); const [isLoadingQuestions, setIsLoadingQuestions] = useState(true); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); const { selectedFeatures, setCurrentStep, projectName, projectType } = useProjectStore(); // Load business questions when component mounts useEffect(() => { loadBusinessQuestions(); }, []); const loadBusinessQuestions = async () => { try { setIsLoadingQuestions(true); setError(null); if (selectedFeatures.length === 0) { setError('No features found to generate business questions'); return; } console.log('🚀 Generating comprehensive business questions for integrated system:', selectedFeatures); // Call the new comprehensive endpoint // Prefer an environment-provided backend URL for frontend builds (REACT_APP_BACKEND_URL or NEXT_PUBLIC_BACKEND_URL). const backendBase = (process.env.REACT_APP_BACKEND_URL || process.env.NEXT_PUBLIC_BACKEND_URL || '').replace(/\/$/, '') || ''; const getApiUrl = (endpoint) => { const clean = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint; if (backendBase) return `${backendBase}/${clean}`; // Fallback to relative path (assumes frontend is served with proxy to backend) return `/${clean}`; }; const response = await fetch(getApiUrl('api/v1/generate-comprehensive-business-questions'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ allFeatures: selectedFeatures, // Send ALL features with their logic rules projectName: projectName, projectType: projectType, totalFeatures: selectedFeatures.length }), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log('✅ Comprehensive business questions response:', data); if (data.success && data.data.businessQuestions) { setBusinessQuestions(data.data.businessQuestions); // Initialize answers object const initialAnswers = {}; data.data.businessQuestions.forEach((question, index) => { initialAnswers[index] = ''; }); setBusinessAnswers(initialAnswers); console.log(`🎯 Generated ${data.data.businessQuestions.length} comprehensive questions for integrated system`); } else { setError('Failed to generate comprehensive business questions'); } } catch (error) { console.error('❌ Error loading comprehensive business questions:', error); setError(`Failed to load business questions: ${error.message}`); } finally { setIsLoadingQuestions(false); } }; const handleAnswerChange = (questionIndex, answer) => { setBusinessAnswers(prev => ({ ...prev, [questionIndex]: answer })); }; const handleSubmit = async () => { try { setIsSubmitting(true); // Validate that at least some questions are answered const answeredQuestions = Object.values(businessAnswers).filter(answer => answer.trim()).length; if (answeredQuestions === 0) { alert('Please answer at least one question before proceeding.'); return; } // Prepare complete data for tech stack selector - use ALL features data const completeData = { // System-wide information projectName: projectName, projectType: projectType, allFeatures: selectedFeatures, // Include ALL features businessQuestions: businessQuestions, businessAnswers: businessAnswers, timestamp: new Date().toISOString(), // For backward compatibility with tech-stack-selector featureName: `${projectName} - Integrated System`, description: `Complete ${projectType} system with ${selectedFeatures.length} integrated features`, requirements: selectedFeatures.flatMap(f => f.requirements || []), complexity: selectedFeatures.some(f => f.complexity === 'high') ? 'high' : selectedFeatures.some(f => f.complexity === 'medium') ? 'medium' : 'low', logicRules: selectedFeatures.flatMap(f => f.logicRules || []) }; console.log('🚀 Sending comprehensive system data to tech stack selector:', completeData); // Call enhanced tech stack selector directly const response = await fetch('https://backend.codenuk.com/api/v1/select', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(completeData), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const techRecommendations = await response.json(); console.log('✅ Tech stack recommendations received:', techRecommendations); // Store results in project store useProjectStore.setState({ finalProjectData: completeData, techStackRecommendations: techRecommendations, businessQuestionsCompleted: true }); // Move to summary step to show recommendations setCurrentStep('summary'); } catch (error) { console.error('❌ Error calling tech stack selector:', error); alert(`Failed to get technology recommendations: ${error.message}`); } finally { setIsSubmitting(false); } }; const handleBack = () => { setCurrentStep('features'); }; if (isLoadingQuestions) { return (
🧠 AI is generating comprehensive business questions...
Analyzing {selectedFeatures.length} features as integrated system
{error}
Help us recommend the best technology stack by answering these questions
Analyzing your complete {projectType} system with {selectedFeatures.length} integrated features
Tip: Answer as many questions as possible for better technology recommendations. You can skip questions you're unsure about. These questions consider your entire system, not individual features.
Questions answered: {Object.values(businessAnswers).filter(answer => answer.trim()).length} of {businessQuestions.length}
Completion: {Math.round((Object.values(businessAnswers).filter(answer => answer.trim()).length / businessQuestions.length) * 100)}%
Features analyzing: {selectedFeatures.length} integrated features