import { useState, useEffect, useRef } from 'react';
import {
MessageSquare, Send, Loader2, History, ArrowLeft, Trash2, BarChart, PieChart,
TrendingUp, Zap, User, LogOut, Mail, Lock, UserPlus, LogIn, ChevronRight,
ChevronDown, Check, Calendar, Clock, DollarSign, Briefcase, Heart, Home,
BarChart2, GitBranch, Sliders, Users, AlertTriangle, Award, BookOpen,
CheckCircle, Compass, FileText, HelpCircle, Layers, Maximize2, Minimize2,
Paperclip, Percent, RefreshCw, Save, Settings, Share2, Star, ThumbsUp,
TrendingDown, X, Bell, Clipboard, Eye, Filter, Map, Plus, Target
} from 'lucide-react';
// Mock data for visualizations
const generateMockData = (type) => {
switch(type) {
case 'riskReward':
return [
{ name: 'Option A', risk: 35, reward: 65, size: 100 },
{ name: 'Option B', risk: 60, reward: 85, size: 100 },
{ name: 'Option C', risk: 20, reward: 40, size: 100 },
];
case 'timeline':
return [
{ name: 'Research', start: 0, duration: 2, category: 'preparation' },
{ name: 'Planning', start: 2, duration: 1, category: 'preparation' },
{ name: 'Implementation', start: 3, duration: 3, category: 'execution' },
{ name: 'Review', start: 6, duration: 1, category: 'evaluation' },
{ name: 'Adjustment', start: 7, duration: 2, category: 'execution' },
];
case 'sensitivity':
return [
{ factor: 'Risk Tolerance', current: 0, min: -2, max: 2, step: 0.5, impact: 'high' },
{ factor: 'Time Horizon', current: 0, min: -2, max: 2, step: 0.5, impact: 'medium' },
{ factor: 'Financial Stability', current: 0, min: -2, max: 2, step: 0.5, impact: 'high' },
{ factor: 'Career Growth', current: 0, min: -2, max: 2, step: 0.5, impact: 'medium' },
{ factor: 'Work-Life Balance', current: 0, min: -2, max: 2, step: 0.5, impact: 'low' },
];
case 'peerInsights':
return {
optionA: 35,
optionB: 65,
satisfactionA: 70,
satisfactionB: 85,
sampleSize: 124,
confidence: 'high'
};
default:
return [];
}
};
// Mock implementation roadmap data
const mockRoadmapData = {
phases: [
{
name: 'Preparation',
tasks: [
{ name: 'Research market conditions', duration: '1-2 weeks', status: 'pending' },
{ name: 'Consult with financial advisor', duration: '1 day', status: 'pending' },
{ name: 'Review current portfolio', duration: '3 days', status: 'pending' }
]
},
{
name: 'Decision Execution',
tasks: [
{ name: 'Finalize investment amount', duration: '1 day', status: 'pending' },
{ name: 'Complete paperwork', duration: '1 week', status: 'pending' },
{ name: 'Transfer funds', duration: '3-5 business days', status: 'pending' }
]
},
{
name: 'Follow-up',
tasks: [
{ name: 'Set up monitoring system', duration: '1 day', status: 'pending' },
{ name: 'Schedule quarterly review', duration: '30 minutes', status: 'pending' },
{ name: 'Document decision rationale', duration: '1 hour', status: 'pending' }
]
}
]
};
// Mock resource links
const mockResourceLinks = [
{ title: 'Understanding Risk Tolerance', url: '#', source: 'Financial Planning Association', type: 'article' },
{ title: 'Investment Strategies for Volatile Markets', url: '#', source: 'Market Analysis Institute', type: 'research' },
{ title: 'Tax Implications of Different Investment Vehicles', url: '#', source: 'Tax Planning Resources', type: 'guide' },
{ title: 'Retirement Calculator', url: '#', source: 'Financial Tools Hub', type: 'tool' },
{ title: 'Historical Market Performance Data', url: '#', source: 'Economic Research Center', type: 'data' }
];
// Decision categories with specialized factors
const decisionCategories = [
{
id: 'career',
name: 'Career',
icon: ,
factors: ['Salary & Benefits', 'Growth Potential', 'Work-Life Balance', 'Company Culture', 'Industry Outlook', 'Location', 'Job Security']
},
{
id: 'financial',
name: 'Financial',
icon: ,
factors: ['Return Potential', 'Risk Level', 'Time Horizon', 'Liquidity Needs', 'Tax Implications', 'Diversification Impact', 'Fees & Costs']
},
{
id: 'personal',
name: 'Personal',
icon: ,
factors: ['Emotional Impact', 'Relationship Effects', 'Health Considerations', 'Personal Values Alignment', 'Time Commitment', 'Social Impact', 'Long-term Happiness']
},
{
id: 'business',
name: 'Business',
icon: ,
factors: ['Market Opportunity', 'Competitive Advantage', 'Resource Requirements', 'Scalability', 'Regulatory Considerations', 'Team Capabilities', 'ROI Projections']
},
{
id: 'housing',
name: 'Housing',
icon: ,
factors: ['Location Quality', 'Property Value Trends', 'Monthly Costs', 'Space Requirements', 'Commute Impact', 'School Districts', 'Neighborhood Amenities']
}
];
// Perspective types for multiple perspective analysis
const perspectiveTypes = [
{ id: 'financial', name: 'Financial Advisor', icon: },
{ id: 'career', name: 'Career Coach', icon: },
{ id: 'industry', name: 'Industry Expert', icon: },
{ id: 'future', name: 'Future Self (5 Years)', icon: },
{ id: 'risk', name: 'Risk Analyst', icon: }
];
export default function PremiumGUTDecisionMaker() {
// Authentication states
const [authState, setAuthState] = useState('login'); // 'login', 'signup', or 'authenticated'
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [name, setName] = useState('');
const [currentUser, setCurrentUser] = useState(null);
const [authError, setAuthError] = useState(null);
// App states
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [conversations, setConversations] = useState([]);
const [currentConversation, setCurrentConversation] = useState({ id: Date.now(), title: 'New Decision', messages: [] });
const [showHistory, setShowHistory] = useState(false);
const [error, setError] = useState(null);
const [showUserMenu, setShowUserMenu] = useState(false);
// Premium features states
const [activeView, setActiveView] = useState('chat'); // 'chat', 'builder', 'analysis', 'journal', 'roadmap'
const [selectedCategory, setSelectedCategory] = useState(null);
const [scenarioData, setScenarioData] = useState({});
const [builderStep, setBuilderStep] = useState(0);
const [activePerspective, setActivePerspective] = useState('financial');
const [showResourcePanel, setShowResourcePanel] = useState(false);
const [sensitivityFactors, setSensitivityFactors] = useState(generateMockData('sensitivity'));
const [confidenceScore, setConfidenceScore] = useState(87);
const [peerInsights, setPeerInsights] = useState(generateMockData('peerInsights'));
const [implementationPlan, setImplementationPlan] = useState(mockRoadmapData);
const [resourceLinks, setResourceLinks] = useState(mockResourceLinks);
const [decisionJournal, setDecisionJournal] = useState([]);
const [showMobileMenu, setShowMobileMenu] = useState(false);
const [subscriptionTier, setSubscriptionTier] = useState('premium'); // 'basic', 'premium', 'enterprise'
// Check for existing login on initial load
useEffect(() => {
const savedUser = localStorage.getItem('gutCurrentUser');
if (savedUser) {
try {
const parsedUser = JSON.parse(savedUser);
setCurrentUser(parsedUser);
setAuthState('authenticated');
setName(parsedUser.name);
// Load user-specific conversations
loadUserConversations(parsedUser.email);
// Load decision journal
loadDecisionJournal(parsedUser.email);
} catch (e) {
console.error('Error parsing saved user:', e);
localStorage.removeItem('gutCurrentUser');
}
}
}, []);
// Load user-specific conversations
const loadUserConversations = (userEmail) => {
try {
const savedConversations = localStorage.getItem(`gutConversations_${userEmail}`);
if (savedConversations) {
setConversations(JSON.parse(savedConversations));
} else {
setConversations([]);
}
} catch (e) {
console.error('Error loading conversations:', e);
setConversations([]);
}
};
// Load decision journal
const loadDecisionJournal = (userEmail) => {
try {
const savedJournal = localStorage.getItem(`gutJournal_${userEmail}`);
if (savedJournal) {
setDecisionJournal(JSON.parse(savedJournal));
} else {
// Initialize with sample data for demo purposes
const sampleJournal = [
{
id: 'j1',
title: 'Job Offer Decision',
category: 'career',
date: '2023-10-15',
decision: 'Accepted startup offer',
outcome: 'Positive',
notes: 'The risk paid off. Gained valuable experience and equity has appreciated.',
followUpDate: '2024-04-15'
},
{
id: 'j2',
title: 'Investment Portfolio Rebalance',
category: 'financial',
date: '2023-11-22',
decision: 'Increased tech allocation by 10%',
outcome: 'Mixed',
notes: 'Initial volatility but trending positive now. Need longer timeframe to fully evaluate.',
followUpDate: '2024-05-22'
},
{
id: 'j3',
title: 'Relocation Decision',
category: 'personal',
date: '2023-08-05',
decision: 'Moved to Austin',
outcome: 'Positive',
notes: 'Better quality of life, though miss friends from previous location. Career opportunities exceeded expectations.',
followUpDate: '2024-02-05'
}
];
setDecisionJournal(sampleJournal);
localStorage.setItem(`gutJournal_${userEmail}`, JSON.stringify(sampleJournal));
}
} catch (e) {
console.error('Error loading decision journal:', e);
setDecisionJournal([]);
}
};
// Save conversations to localStorage whenever they change
useEffect(() => {
if (currentUser && currentUser.email) {
try {
localStorage.setItem(`gutConversations_${currentUser.email}`, JSON.stringify(conversations));
} catch (e) {
console.error('Error saving conversations:', e);
}
}
}, [conversations, currentUser]);
// Save decision journal to localStorage whenever it changes
useEffect(() => {
if (currentUser && currentUser.email) {
try {
localStorage.setItem(`gutJournal_${currentUser.email}`, JSON.stringify(decisionJournal));
} catch (e) {
console.error('Error saving decision journal:', e);
}
}
}, [decisionJournal, currentUser]);
// Authentication functions
const handleLogin = (e) => {
e.preventDefault();
setAuthError(null);
try {
// In a real app, this would be an API call to your backend
const users = JSON.parse(localStorage.getItem('gutUsers') || '[]');
const user = users.find(u => u.email === email);
if (!user) {
setAuthError('No account found with this email');
return;
}
if (user.password !== password) {
setAuthError('Incorrect password');
return;
}
// Login successful
setCurrentUser(user);
setAuthState('authenticated');
setName(user.name);
// Save current user to localStorage
localStorage.setItem('gutCurrentUser', JSON.stringify(user));
// Load user-specific conversations
loadUserConversations(user.email);
// Load decision journal
loadDecisionJournal(user.email);
// Reset form
setEmail('');
setPassword('');
} catch (e) {
console.error('Login error:', e);
setAuthError('An error occurred during login');
}
};
const handleSignup = (e) => {
e.preventDefault();
setAuthError(null);
// Validate form
if (!name.trim()) {
setAuthError('Please enter your name');
return;
}
if (!email.trim()) {
setAuthError('Please enter your email');
return;
}
if (!password) {
setAuthError('Please enter a password');
return;
}
if (password !== confirmPassword) {
setAuthError('Passwords do not match');
return;
}
try {
// In a real app, this would be an API call to your backend
const users = JSON.parse(localStorage.getItem('gutUsers') || '[]');
// Check if email already exists
if (users.some(u => u.email === email)) {
setAuthError('An account with this email already exists');
return;
}
// Create new user
const newUser = {
name,
email,
password,
createdAt: new Date().toISOString(),
subscription: {
tier: 'premium', // Default to premium for demo
startDate: new Date().toISOString(),
endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString() // 30 days trial
}
};
users.push(newUser);
// Save updated users list
localStorage.setItem('gutUsers', JSON.stringify(users));
// Auto-login after signup
setCurrentUser(newUser);
setAuthState('authenticated');
// Save current user to localStorage
localStorage.setItem('gutCurrentUser', JSON.stringify(newUser));
// Initialize empty conversations for new user
setConversations([]);
localStorage.setItem(`gutConversations_${email}`, JSON.stringify([]));
// Initialize empty decision journal
setDecisionJournal([]);
localStorage.setItem(`gutJournal_${email}`, JSON.stringify([]));
// Reset form
setName('');
setEmail('');
setPassword('');
setConfirmPassword('');
} catch (e) {
console.error('Signup error:', e);
setAuthError('An error occurred during signup');
}
};
const handleLogout = () => {
setCurrentUser(null);
setAuthState('login');
localStorage.removeItem('gutCurrentUser');
setConversations([]);
setCurrentConversation({ id: Date.now(), title: 'New Decision', messages: [] });
setShowUserMenu(false);
setActiveView('chat');
};
const toggleAuthState = () => {
setAuthState(authState === 'login' ? 'signup' : 'login');
setAuthError(null);
setEmail('');
setPassword('');
setConfirmPassword('');
setName('');
};
// Enhanced mock AI response function for fallback
const getMockResponse = (userMessage) => {
// Create a more sophisticated response based on keywords in the user message
const lowerCaseMessage = userMessage.toLowerCase();
// Career decision template
if (lowerCaseMessage.includes('job') || lowerCaseMessage.includes('career') || lowerCaseMessage.includes('offer') || lowerCaseMessage.includes('position')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're facing a career decision between staying at an established tech company versus joining an AI healthcare startup. This is a complex decision with significant implications for your financial security, career trajectory, and work-life balance.
## Quantitative Assessment
### Financial Projections (5-Year Outlook)
| Factor | Current Company | AI Healthcare Startup |
|--------|----------------|----------------------|
| Base Salary | $120,000 with 3% annual increases | $105,000 with potential for rapid growth |
| Bonus Potential | 10-15% annually, reliable | 5-10% initially, potentially higher later |
| Equity Value | ~$50,000 vested | $200,000-$800,000 (high variability) |
| Risk-Adjusted Total | $725,000 | $650,000-$1.2M |
### Risk Assessment
* **Current Position**: 85% probability of continued stability, 10% probability of limited advancement, 5% probability of downsizing
* **Startup Option**: 30% probability of significant success, 40% probability of moderate success, 30% probability of failure/acquisition with limited returns
## Industry Context Analysis
The traditional tech sector is showing signs of maturation with 7-12% annual growth, while AI healthcare specifically is projected to grow at 28% CAGR over the next decade. However, regulatory hurdles in healthcare create significant execution risks that could delay returns.
## Personal Circumstances Evaluation
Your current mortgage ($2,800/month) and family planning timeline (next 2-3 years) suggest a need for income stability in the short term. Your partner's business is still in growth phase, creating a household income volatility factor that should be considered.
## Trade-off Analysis
**What You Gain with Current Company:**
* Financial predictability during family planning years
* Established work-life boundaries and policies
* Proven career advancement path
* Lower stress during significant life changes
**What You Gain with Startup:**
* Potential for 3-5x greater equity upside
* Accelerated skill development in emerging field
* Greater autonomy and impact scope
* Positioning in high-growth sector for future opportunities
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Financial security (35%): Current company scores higher
2. Long-term growth potential (25%): Startup scores higher
3. Work-life balance (20%): Current company scores higher
4. Professional fulfillment (20%): Startup scores higher
Weighted total: Current company (7.6/10) vs. Startup (7.2/10)
## Risk Mitigation Strategies
If choosing the startup:
* Negotiate a severance package
* Build 9-month emergency fund before transitioning
* Secure written agreement on flexible hours during family planning period
* Maintain active network in established tech companies
## GUT Feeling
When analyzing all factors, your optimal path likely depends on your risk tolerance during this life stage. The data suggests your current position provides more appropriate stability for your near-term family goals, while the startup represents a calculated risk with higher potential returns.
Trust your gut: Your hesitation about the startup during family planning years seems well-founded in the data. The stability of your current position aligns with your immediate life priorities, though maintaining connections to the AI healthcare space through side projects could position you for a transition in 3-4 years when family needs may be more predictable.
GUT`;
}
// Financial decision template
else if (lowerCaseMessage.includes('invest') || lowerCaseMessage.includes('buy') || lowerCaseMessage.includes('purchase') || lowerCaseMessage.includes('money')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're considering a significant financial decision regarding property investment versus market investments. This decision impacts your long-term financial security, liquidity needs, and wealth-building strategy.
## Quantitative Assessment
### 10-Year Projection Comparison
| Factor | Real Estate Investment | Market Investment Portfolio |
|--------|------------------------|----------------------------|
| Initial Investment | $80,000 down payment | $80,000 full investment |
| Projected Annual Return | 4.7% appreciation + 2.3% rental yield | 7.2% average (based on diversified portfolio) |
| Liquidity | Low (3-6 months to liquidate) | High (2-3 days for most assets) |
| Tax Implications | Depreciation benefits, 1031 exchange potential | Capital gains tax, dividend taxation |
| Total Projected Value | $215,000-$240,000 | $160,000-$190,000 |
| Risk-Adjusted Value | $195,000 | $175,000 |
### Risk Assessment
* **Real Estate Option**: 65% probability of projected returns, 25% probability of underperformance, 10% probability of significant appreciation
* **Market Portfolio**: 60% probability of projected returns, 25% probability of underperformance, 15% probability of significant outperformance
## Market Context Analysis
The current real estate market in your area shows a price-to-rent ratio of 19, slightly above the historical average of 17, suggesting moderate overvaluation. Interest rates at 4.5% are favorable for financing but projected to rise to 5.5% within 18 months.
The equity markets are trading at a P/E ratio of 22, above the historical average of 16, indicating potential for limited growth in the near term but strong corporate earnings support long-term prospects.
## Personal Financial Situation
Your current debt-to-income ratio of 28% provides adequate flexibility for real estate investment. Your emergency fund covers 4 months of expenses, which is below the recommended 6 months if taking on additional property debt.
## Trade-off Analysis
**What You Gain with Real Estate:**
* Physical asset with utility value
* Potential for leveraged returns
* Inflation hedge characteristics
* Tax advantages through depreciation
* Potential passive income stream
**What You Gain with Market Portfolio:**
* Superior liquidity
* Lower transaction costs (2% vs 8-10%)
* Diversification across sectors and geographies
* Lower time commitment for management
* Easier incremental investment capability
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Long-term appreciation (30%): Both options score similarly
2. Income generation (25%): Real estate scores higher
3. Liquidity needs (20%): Market portfolio scores higher
4. Management simplicity (15%): Market portfolio scores higher
5. Tax efficiency (10%): Real estate scores higher
Weighted total: Real Estate (7.3/10) vs. Market Portfolio (7.1/10)
## Risk Mitigation Strategies
If choosing real estate:
* Increase emergency fund to 8 months before purchasing
* Select property with strong rental demand history
* Budget 5% of property value annually for maintenance
* Consider property management (7-10% of rental income)
## GUT Feeling
The quantitative analysis shows these options are remarkably balanced for your situation. However, your personal comfort with active management and your desire for tangible assets suggest real estate aligns better with your temperament and goals.
Trust your gut: Your interest in real estate isn't just about the numbers—it reflects your desire for concrete investments you can see and influence directly. This psychological comfort with real assets may provide intangible benefits that make real estate the better choice for you, despite the slightly higher management burden.
GUT`;
}
// Relationship decision template
else if (lowerCaseMessage.includes('relationship') || lowerCaseMessage.includes('partner') || lowerCaseMessage.includes('marry') || lowerCaseMessage.includes('move')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're considering relocating to be closer to your partner, which involves significant career, social, and lifestyle changes. This decision impacts multiple dimensions of your life with both immediate and long-term consequences.
## Quantitative Assessment
### Comprehensive Life Impact Analysis
| Factor | Current Location | Partner's Location |
|--------|-----------------|-------------------|
| Career Opportunity Index | 85/100 (current trajectory) | 70/100 (new market) |
| Cost of Living Adjustment | Baseline | +15% higher expenses |
| Social Connection Strength | 90/100 (established) | 40/100 (developing) |
| Relationship Proximity Value | 30/100 (distance strain) | 95/100 (daily connection) |
| Overall Life Satisfaction Projection | 68/100 | 74/100 |
### Transition Cost Analysis
* Relocation expenses: $8,000-$12,000
* Income disruption: 2-4 months of adjustment ($14,000-$28,000)
* New housing setup: $5,000-$7,000
* Social rebuilding investment: $3,000-$5,000 (activities, memberships)
* Total transition investment: $30,000-$52,000
## Relationship Context Analysis
Your relationship has demonstrated stability over 2.5 years with effective communication patterns and aligned core values (85% compatibility on major life goals). The distance factor has been the primary stressor, with communication quality declining 35% during separation periods longer than 3 weeks.
## Career Impact Evaluation
Your industry presence in the new location ranks at 65% of your current market, with 15% fewer opportunities at your experience level. However, remote work options have increased by 140% in your field since 2020, potentially mitigating location disadvantages.
## Trade-off Analysis
**What You Gain with Relocation:**
* Daily in-person connection with partner (+65% relationship interaction time)
* Potential for relationship progression to next stages
* New professional network and perspective
* Fresh environment and lifestyle opportunities
* Resolution of distance-related relationship stress
**What You Sacrifice with Relocation:**
* Established professional network strength
* Proximity to family and friends (7 close connections vs. 2)
* Career momentum in current role
* Financial efficiency (15% higher living costs)
* Independence and established routines
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Relationship health (40%): Relocation scores significantly higher
2. Career development (25%): Current location scores moderately higher
3. Social connections (20%): Current location scores higher
4. Financial optimization (15%): Current location scores higher
Weighted total: Current Location (6.8/10) vs. Relocation (7.7/10)
## Risk Mitigation Strategies
If choosing relocation:
* Negotiate remote work arrangement before moving
* Plan quarterly visits back to maintain professional network
* Create structured timeline for career transition
* Establish clear financial partnership terms with significant other
* Develop 90-day social integration plan for new location
## GUT Feeling
The analysis suggests that despite the tangible costs and career adjustments of relocation, the relationship benefits create a higher projected life satisfaction. Your consistent prioritization of relationship factors in our discussion indicates this aligns with your core values.
Trust your gut: The anxiety you feel appears focused on the logistics and career unknowns rather than the relationship decision itself. This suggests your intuition is already aligned with moving forward with the relocation, but needs reassurance about the practical execution.
GUT`;
}
// General decision template (fallback)
else {
return `# Analytical Decision Breakdown
## Situation Analysis
You're facing a complex decision with multiple variables and significant potential impact on your future trajectory. This requires balancing immediate considerations with long-term implications across several life dimensions.
## Quantitative Assessment
### Impact Projection (3-Year Outlook)
| Factor | Option A | Option B |
|--------|----------|----------|
| Financial Impact | Moderate upside (+15-20%) | Higher variability (-10% to +40%) |
| Time Investment | 25-30 hours weekly | 40-50 hours weekly initially, reducing over time |
| Skill Development | Incremental growth in established areas | Accelerated growth in new domains |
| Network Expansion | Limited to current industry | Cross-sector expansion potential |
| Stress/Wellbeing Impact | Minimal adjustment required | Significant adaptation period (6-9 months) |
### Risk Assessment
* **Option A**: 75% probability of moderate success, 20% probability of stagnation, 5% probability of exceptional outcomes
* **Option B**: 40% probability of significant success, 35% probability of moderate success, 25% probability of setbacks requiring course correction
## Contextual Analysis
Current trends in your situation suggest a 7% annual growth in opportunities related to Option B, compared to 3% for Option A. However, the established foundation you have for Option A provides a 35% higher baseline starting advantage.
## Personal Circumstances Evaluation
Your current commitments, energy levels, and support systems align 70% with the requirements of Option A and 55% with Option B. However, your expressed values and long-term aspirations align 60% with Option A and 85% with Option B.
## Trade-off Analysis
**What You Gain with Option A:**
* Greater certainty and predictability
* Lower initial stress and adaptation requirements
* Continued leverage of established strengths
* More immediate positive feedback
* Better work-life balance in the short term
**What You Gain with Option B:**
* Higher ceiling for long-term outcomes
* Development of new capabilities and perspectives
* Expanded identity and self-concept
* Greater alignment with expressed future aspirations
* More diverse opportunities downstream
## Decision Framework
Using a weighted decision matrix with standard life priorities:
1. Long-term fulfillment (30%): Option B scores higher
2. Short-term wellbeing (25%): Option A scores higher
3. Financial security (20%): Both score similarly with different patterns
4. Personal growth (15%): Option B scores higher
5. Relationship impacts (10%): Option A scores moderately higher
Weighted total: Option A (7.2/10) vs. Option B (7.6/10)
## Risk Mitigation Strategies
If choosing Option B:
* Create a 90-day adaptation plan with clear milestones
* Identify specific support resources before beginning
* Establish boundaries to protect core wellbeing needs
* Develop contingency plans for the most challenging aspects
* Schedule regular reassessment points to evaluate progress
## GUT Feeling
The analysis reveals that while Option A offers more comfort and certainty, Option B better aligns with your expressed deeper values and aspirations. The discomfort associated with Option B appears to be primarily related to the transition rather than the destination.
Trust your gut: Your hesitation about Option B seems centered on the fear of change rather than doubts about its alignment with your authentic self. When you envision yourself one year into either path, notice which creates a sense of expansion versus which creates a sense of safety but potential regret.
GUT`;
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
setError(null);
// Add user message to current conversation
const updatedMessages = [
...currentConversation.messages,
{ role: 'user', content: input }
];
// Update conversation with user message
const updatedConversation = {
...currentConversation,
messages: updatedMessages,
title: currentConversation.messages.length === 0 ? input.slice(0, 30) + (input.length > 30 ? '...' : '') : currentConversation.title
};
setCurrentConversation(updatedConversation);
setInput('');
setIsLoading(true);
try {
// Sophisticated system prompt for detailed analytical responses
const systemPrompt = `You are GUT, an advanced decision-making AI assistant that provides sophisticated, data-driven analysis combined with intuitive guidance.
Your responses must include TWO distinct sections:
1. ANALYTICAL DECISION BREAKDOWN (80% of your response):
- Begin with a concise situation analysis
- Provide quantitative assessments including financial projections, probability estimates, and comparative metrics
- Include relevant industry/context analysis with specific data points and trends
- Directly reference the user's personal circumstances and how they affect the decision
- Present a detailed trade-off analysis comparing what is gained and lost with each option
- Use a structured decision framework showing how you reached your conclusion
- Suggest specific risk mitigation strategies for the recommended path
- Use tables, bullet points, and clear headings to organize information
- Include specific numbers, percentages, and timeframes wherever possible
2. GUT FEELING (20% of your response):
- Provide an intuitive summary that synthesizes the analysis
- Highlight the emotional and values-based aspects of the decision
- Offer a clear perspective on what the user's hesitation or enthusiasm might indicate
- End with "Trust your gut:" followed by a final insight about their decision
Your response should feel like a combination of a management consultant's analysis and a trusted mentor's advice. Be specific, data-driven, and personalized to their exact situation. Avoid generic advice.
Sign your response simply with "GUT" at the very end.`;
// Prepare messages for API
const apiMessages = [
{ role: 'system', content: systemPrompt },
...updatedMessages
];
let aiResponse;
try {
// Try to make API request
const response = await fetch('https://www.sitebrew.ai/api/ahwmkN/genai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ messages: apiMessages }),
});
if (!response.ok) {
throw new Error(`API responded with status: ${response.status}`);
}
const data = await response.json();
if (data && data.message && data.message.content) {
aiResponse = data.message.content;
} else {
throw new Error('Invalid response format from API');
}
} catch (apiError) {
console.error('API Error:', apiError);
// Fallback to enhanced mock response
aiResponse = getMockResponse(input);
}
// Add AI response to conversation
const finalConversation = {
...updatedConversation,
messages: [
...updatedConversation.messages,
{ role: 'assistant', content: aiResponse }
]
};
setCurrentConversation(finalConversation);
// Update conversations list
const conversationIndex = conversations.findIndex(c => c.id === currentConversation.id);
if (conversationIndex >= 0) {
const newConversations = [...conversations];
newConversations[conversationIndex] = finalConversation;
setConversations(newConversations);
} else {
setConversations([...conversations, finalConversation]);
}
// For demo purposes, automatically generate scenario data based on the conversation
if (currentConversation.messages.length === 0) {
generateScenarioFromConversation(finalConversation);
}
} catch (error) {
console.error('Error in handleSubmit:', error);
setError('Something went wrong. Please try again.');
// Add error message to conversation
const errorConversation = {
...updatedConversation,
messages: [
...updatedConversation.messages,
{ role: 'assistant', content: "I'm sorry, I couldn't connect with GUT right now. Please try again later." }
]
};
setCurrentConversation(errorConversation);
} finally {
setIsLoading(false);
}
};
// Generate scenario data from conversation for demo purposes
const generateScenarioFromConversation = (conversation) => {
const userMessage = conversation.messages[0].content.toLowerCase();
if (userMessage.includes('job') || userMessage.includes('career') || userMessage.includes('offer')) {
setSelectedCategory(decisionCategories.find(c => c.id === 'career'));
setScenarioData({
title: 'Career Decision',
options: ['Current Company', 'AI Healthcare Startup'],
factors: [
{ name: 'Salary & Benefits', optionA: 8, optionB: 6, weight: 3 },
{ name: 'Growth Potential', optionA: 5, optionB: 9, weight: 4 },
{ name: 'Work-Life Balance', optionA: 7, optionB: 4, weight: 3 },
{ name: 'Company Culture', optionA: 6, optionB: 8, weight: 2 },
{ name: 'Job Security', optionA: 8, optionB: 4, weight: 3 }
],
context: {
timeframe: '5 years',
location: 'San Francisco',
constraints: 'Family planning in 2-3 years, mortgage payments'
}
});
} else if (userMessage.includes('invest') || userMessage.includes('financial') || userMessage.includes('money')) {
setSelectedCategory(decisionCategories.find(c => c.id === 'financial'));
setScenarioData({
title: 'Investment Decision',
options: ['Real Estate', 'Market Portfolio'],
factors: [
{ name: 'Return Potential', optionA: 7, optionB: 8, weight: 4 },
{ name: 'Risk Level', optionA: 5, optionB: 7, weight: 3 },
{ name: 'Liquidity', optionA: 3, optionB: 9, weight: 2 },
{ name: 'Tax Advantages', optionA: 8, optionB: 5, weight: 2 },
{ name: 'Management Effort', optionA: 4, optionB: 8, weight: 3 }
],
context: {
timeframe: '10 years',
amount: '$80,000',
constraints: 'Need some liquidity for potential home purchase in 3-5 years'
}
});
} else if (userMessage.includes('relationship') || userMessage.includes('partner') || userMessage.includes('move')) {
setSelectedCategory(decisionCategories.find(c => c.id === 'personal'));
setScenarioData({
title: 'Relocation Decision',
options: ['Current Location', 'Partner\'s Location'],
factors: [
{ name: 'Relationship Quality', optionA: 5, optionB: 9, weight: 4 },
{ name: 'Career Opportunities', optionA: 8, optionB: 6, weight: 3 },
{ name: 'Social Connections', optionA: 9, optionB: 4, weight: 2 },
{ name: 'Cost of Living', optionA: 7, optionB: 5, weight: 2 },
{ name: 'Quality of Life', optionA: 6, optionB: 7, weight: 3 }
],
context: {
timeframe: 'Long-term',
relationship: '2.5 years',
constraints: 'Career momentum, established social network'
}
});
} else {
setSelectedCategory(decisionCategories.find(c => c.id === 'personal'));
setScenarioData({
title: 'General Decision',
options: ['Option A', 'Option B'],
factors: [
{ name: 'Short-term Impact', optionA: 7, optionB: 5, weight: 3 },
{ name: 'Long-term Potential', optionA: 5, optionB: 8, weight: 4 },
{ name: 'Risk Level', optionA: 3, optionB: 7, weight: 3 },
{ name: 'Alignment with Values', optionA: 6, optionB: 8, weight: 4 },
{ name: 'Resource Requirements', optionA: 7, optionB: 4, weight: 2 }
],
context: {
timeframe: '3 years',
constraints: 'Current commitments, energy levels, support systems'
}
});
}
};
const startNewConversation = () => {
const newConversation = { id: Date.now(), title: 'New Decision', messages: [] };
setCurrentConversation(newConversation);
setShowHistory(false);
setActiveView('chat');
setSelectedCategory(null);
setScenarioData({});
setBuilderStep(0);
};
const loadConversation = (conversation) => {
setCurrentConversation(conversation);
setShowHistory(false);
setActiveView('chat');
// For demo purposes, generate scenario data if it doesn't exist
if (conversation.messages.length > 0) {
generateScenarioFromConversation(conversation);
}
};
const deleteConversation = (id, e) => {
e.stopPropagation();
const newConversations = conversations.filter(c => c.id !== id);
setConversations(newConversations);
if (currentConversation.id === id) {
startNewConversation();
}
};
// Enhanced markdown rendering function
const renderMarkdown = (content) => {
return { __html: content
// Headers
.replace(/^# (.*$)/gm, '
"The quantitative analysis favors {recommendedOption}, but consider how this choice aligns with your core values and long-term vision. Your hesitation may be signaling important considerations that aren't captured in the numbers."
Trust your gut
Trade-off Analysis
What You Gain with {(scenarioData.options && scenarioData.options[0]) || 'Option A'}
From a financial perspective, this decision should be evaluated primarily on risk-adjusted returns, liquidity needs, and long-term wealth building potential.
Key Financial Considerations
The net present value (NPV) of {(scenarioData.options && scenarioData.options[0]) || 'Option A'} is approximately 15% higher when adjusted for risk.
While {(scenarioData.options && scenarioData.options[1]) || 'Option B'} has higher potential upside, the probability-weighted return is lower.
Your current debt-to-income ratio suggests maintaining liquidity should be prioritized over the next 12-18 months.
Tax implications favor {(scenarioData.options && scenarioData.options[0]) || 'Option A'} by approximately 8% over a 5-year horizon.
Financial Recommendation
Based purely on financial analysis, {(scenarioData.options && scenarioData.options[0]) || 'Option A'} provides the optimal balance of risk and return given your current financial situation and stated goals.
Alternative Strategy
Consider a hybrid approach: Allocate 70% of resources to {(scenarioData.options && scenarioData.options[0]) || 'Option A'} while testing {(scenarioData.options && scenarioData.options[1]) || 'Option B'} with the remaining 30% to maintain optionality.
)}
{activePerspective === 'career' && (
From a career development perspective, this decision should be evaluated based on skill acquisition, network building, industry positioning, and long-term career capital.
Key Career Considerations
{(scenarioData.options && scenarioData.options[1]) || 'Option B'} offers 3x more exposure to emerging technologies that are projected to dominate the industry within 5 years.
The leadership experience available in {(scenarioData.options && scenarioData.options[0]) || 'Option A'} provides valuable management credentials for future roles.
Your career trajectory shows you're at an inflection point where specialized expertise (favoring {(scenarioData.options && scenarioData.options[1]) || 'Option B'}) could differentiate you in the market.
The network you'd build in {(scenarioData.options && scenarioData.options[1]) || 'Option B'} includes more founders and innovators, while {(scenarioData.options && scenarioData.options[0]) || 'Option A'} connects you with more established executives.
Career Recommendation
From a pure career development standpoint, {(scenarioData.options && scenarioData.options[1]) || 'Option B'} positions you better for the future direction of your industry, despite short-term stability trade-offs.
Career Risk Mitigation
If choosing {(scenarioData.options && scenarioData.options[1]) || 'Option B'}, maintain your professional brand through speaking engagements, publishing, and industry association leadership to preserve optionality.
)}
{activePerspective === 'industry' && (
From an industry expert perspective, this decision should be evaluated based on market trends, competitive dynamics, and sector-specific opportunities and threats.
Industry Analysis
The sector related to {(scenarioData.options && scenarioData.options[1]) || 'Option B'} is growing at 28% CAGR compared to 7-12% for {(scenarioData.options && scenarioData.options[0]) || 'Option A'}.
Regulatory changes expected in the next 18-24 months will likely favor established players like those in {(scenarioData.options && scenarioData.options[0]) || 'Option A'}.
Talent shortages in the {(scenarioData.options && scenarioData.options[1]) || 'Option B'} space are creating premium compensation packages that may be unsustainable.
Consolidation trends suggest companies like those in {(scenarioData.options && scenarioData.options[0]) || 'Option A'} will be acquirers rather than targets in the next market cycle.
Industry Recommendation
Industry analysis suggests {(scenarioData.options && scenarioData.options[1]) || 'Option B'} offers better positioning for long-term industry trends, despite near-term volatility and execution challenges.
Industry Context
The industry is at an inflection point where emerging technologies are disrupting traditional business models. Early movers in these new spaces (like {(scenarioData.options && scenarioData.options[1]) || 'Option B'}) have historically captured disproportionate value.
)}
{activePerspective === 'future' && (
From your future self's perspective (5 years from now), this decision should be evaluated based on how it shapes your options, experiences, and position in the long run.
Future Self Reflection
The skills and experiences gained from {(scenarioData.options && scenarioData.options[1]) || 'Option B'} will likely be more valuable and differentiating in 5 years.
The stability of {(scenarioData.options && scenarioData.options[0]) || 'Option A'} may lead to fewer growth challenges but also fewer breakthrough opportunities.
Your future self will likely value the diverse experiences and resilience built through navigating the uncertainty of {(scenarioData.options && scenarioData.options[1]) || 'Option B'}.
The network built through {(scenarioData.options && scenarioData.options[1]) || 'Option B'} will likely open more diverse opportunities in the future.
Future Self Recommendation
Your future self would likely recommend {(scenarioData.options && scenarioData.options[1]) || 'Option B'} despite the short-term challenges, as it builds more valuable career capital and creates more optionality.
Future Regret Minimization
When people reflect on their careers, they more often regret risks not taken rather than calculated risks that didn't fully pay off. The "safe" choice of {(scenarioData.options && scenarioData.options[0]) || 'Option A'} may carry more long-term regret risk.
)}
{activePerspective === 'risk' && (
From a risk analyst perspective, this decision should be evaluated based on probability-weighted outcomes, downside protection, and the full spectrum of potential scenarios.
Risk Assessment
{(scenarioData.options && scenarioData.options[0]) || 'Option A'} has an 85% probability of meeting expectations, while {(scenarioData.options && scenarioData.options[1]) || 'Option B'} has only a 70% probability.
The worst-case scenario for {(scenarioData.options && scenarioData.options[0]) || 'Option A'} is significantly less severe than for {(scenarioData.options && scenarioData.options[1]) || 'Option B'}.
Recovery options are more numerous and accessible if {(scenarioData.options && scenarioData.options[0]) || 'Option A'} underperforms.
Your personal risk capacity is moderately constrained by current commitments, favoring the more predictable outcomes of {(scenarioData.options && scenarioData.options[0]) || 'Option A'}.
Risk Recommendation
From a pure risk management perspective, {(scenarioData.options && scenarioData.options[0]) || 'Option A'} provides a more favorable risk-adjusted outcome given your current circumstances and constraints.
Risk Mitigation Strategy
If you choose {(scenarioData.options && scenarioData.options[1]) || 'Option B'} despite higher risk, implement a robust contingency plan including: 1) Increased emergency savings, 2) Maintaining professional network for quick pivots, and 3) Setting clear milestone checkpoints for reassessment.
The multiple perspectives reveal a tension between short-term security ({(scenarioData.options && scenarioData.options[0]) || 'Option A'}) and long-term potential ({(scenarioData.options && scenarioData.options[1]) || 'Option B'}). Your decision should weigh these time horizons based on your current life stage and personal values.
import { useState, useEffect } from 'react';
import { MessageSquare, Send, Loader2, History, ArrowLeft, Trash2, BarChart, PieChart, TrendingUp, Zap, User, LogOut, Mail, Lock, UserPlus, LogIn } from 'lucide-react';
export default function GUTDecisionMaker() {
// Authentication states
const [authState, setAuthState] = useState('login'); // 'login', 'signup', or 'authenticated'
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [name, setName] = useState('');
const [currentUser, setCurrentUser] = useState(null);
const [authError, setAuthError] = useState(null);
// App states
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [conversations, setConversations] = useState([]);
const [currentConversation, setCurrentConversation] = useState({ id: Date.now(), title: 'New Decision', messages: [] });
const [showHistory, setShowHistory] = useState(false);
const [error, setError] = useState(null);
const [showUserMenu, setShowUserMenu] = useState(false);
// Check for existing login on initial load
useEffect(() => {
const savedUser = localStorage.getItem('gutCurrentUser');
if (savedUser) {
try {
const parsedUser = JSON.parse(savedUser);
setCurrentUser(parsedUser);
setAuthState('authenticated');
setName(parsedUser.name);
// Load user-specific conversations
loadUserConversations(parsedUser.email);
} catch (e) {
console.error('Error parsing saved user:', e);
localStorage.removeItem('gutCurrentUser');
}
}
}, []);
// Load user-specific conversations
const loadUserConversations = (userEmail) => {
try {
const savedConversations = localStorage.getItem(`gutConversations_${userEmail}`);
if (savedConversations) {
setConversations(JSON.parse(savedConversations));
} else {
setConversations([]);
}
} catch (e) {
console.error('Error loading conversations:', e);
setConversations([]);
}
};
// Save conversations to localStorage whenever they change
useEffect(() => {
if (currentUser && currentUser.email) {
try {
localStorage.setItem(`gutConversations_${currentUser.email}`, JSON.stringify(conversations));
} catch (e) {
console.error('Error saving conversations:', e);
}
}
}, [conversations, currentUser]);
// Authentication functions
const handleLogin = (e) => {
e.preventDefault();
setAuthError(null);
try {
// In a real app, this would be an API call to your backend
const users = JSON.parse(localStorage.getItem('gutUsers') || '[]');
const user = users.find(u => u.email === email);
if (!user) {
setAuthError('No account found with this email');
return;
}
if (user.password !== password) {
setAuthError('Incorrect password');
return;
}
// Login successful
setCurrentUser(user);
setAuthState('authenticated');
setName(user.name);
// Save current user to localStorage
localStorage.setItem('gutCurrentUser', JSON.stringify(user));
// Load user-specific conversations
loadUserConversations(user.email);
// Reset form
setEmail('');
setPassword('');
} catch (e) {
console.error('Login error:', e);
setAuthError('An error occurred during login');
}
};
const handleSignup = (e) => {
e.preventDefault();
setAuthError(null);
// Validate form
if (!name.trim()) {
setAuthError('Please enter your name');
return;
}
if (!email.trim()) {
setAuthError('Please enter your email');
return;
}
if (!password) {
setAuthError('Please enter a password');
return;
}
if (password !== confirmPassword) {
setAuthError('Passwords do not match');
return;
}
try {
// In a real app, this would be an API call to your backend
const users = JSON.parse(localStorage.getItem('gutUsers') || '[]');
// Check if email already exists
if (users.some(u => u.email === email)) {
setAuthError('An account with this email already exists');
return;
}
// Create new user
const newUser = { name, email, password, createdAt: new Date().toISOString() };
users.push(newUser);
// Save updated users list
localStorage.setItem('gutUsers', JSON.stringify(users));
// Auto-login after signup
setCurrentUser(newUser);
setAuthState('authenticated');
// Save current user to localStorage
localStorage.setItem('gutCurrentUser', JSON.stringify(newUser));
// Initialize empty conversations for new user
setConversations([]);
localStorage.setItem(`gutConversations_${email}`, JSON.stringify([]));
// Reset form
setName('');
setEmail('');
setPassword('');
setConfirmPassword('');
} catch (e) {
console.error('Signup error:', e);
setAuthError('An error occurred during signup');
}
};
const handleLogout = () => {
setCurrentUser(null);
setAuthState('login');
localStorage.removeItem('gutCurrentUser');
setConversations([]);
setCurrentConversation({ id: Date.now(), title: 'New Decision', messages: [] });
setShowUserMenu(false);
};
const toggleAuthState = () => {
setAuthState(authState === 'login' ? 'signup' : 'login');
setAuthError(null);
setEmail('');
setPassword('');
setConfirmPassword('');
setName('');
};
// Enhanced mock AI response function for fallback
const getMockResponse = (userMessage) => {
// Create a more sophisticated response based on keywords in the user message
const lowerCaseMessage = userMessage.toLowerCase();
// Career decision template
if (lowerCaseMessage.includes('job') || lowerCaseMessage.includes('career') || lowerCaseMessage.includes('offer') || lowerCaseMessage.includes('position')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're facing a career decision between staying at an established tech company versus joining an AI healthcare startup. This is a complex decision with significant implications for your financial security, career trajectory, and work-life balance.
## Quantitative Assessment
### Financial Projections (5-Year Outlook)
| Factor | Current Company | AI Healthcare Startup |
|--------|----------------|----------------------|
| Base Salary | $120,000 with 3% annual increases | $105,000 with potential for rapid growth |
| Bonus Potential | 10-15% annually, reliable | 5-10% initially, potentially higher later |
| Equity Value | ~$50,000 vested | $200,000-$800,000 (high variability) |
| Risk-Adjusted Total | $725,000 | $650,000-$1.2M |
### Risk Assessment
* **Current Position**: 85% probability of continued stability, 10% probability of limited advancement, 5% probability of downsizing
* **Startup Option**: 30% probability of significant success, 40% probability of moderate success, 30% probability of failure/acquisition with limited returns
## Industry Context Analysis
The traditional tech sector is showing signs of maturation with 7-12% annual growth, while AI healthcare specifically is projected to grow at 28% CAGR over the next decade. However, regulatory hurdles in healthcare create significant execution risks that could delay returns.
## Personal Circumstances Evaluation
Your current mortgage ($2,800/month) and family planning timeline (next 2-3 years) suggest a need for income stability in the short term. Your partner's business is still in growth phase, creating a household income volatility factor that should be considered.
## Trade-off Analysis
**What You Gain with Current Company:**
* Financial predictability during family planning years
* Established work-life boundaries and policies
* Proven career advancement path
* Lower stress during significant life changes
**What You Gain with Startup:**
* Potential for 3-5x greater equity upside
* Accelerated skill development in emerging field
* Greater autonomy and impact scope
* Positioning in high-growth sector for future opportunities
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Financial security (35%): Current company scores higher
2. Long-term growth potential (25%): Startup scores higher
3. Work-life balance (20%): Current company scores higher
4. Professional fulfillment (20%): Startup scores higher
Weighted total: Current company (7.6/10) vs. Startup (7.2/10)
## Risk Mitigation Strategies
If choosing the startup:
* Negotiate a severance package
* Build 9-month emergency fund before transitioning
* Secure written agreement on flexible hours during family planning period
* Maintain active network in established tech companies
## GUT Feeling
When analyzing all factors, your optimal path likely depends on your risk tolerance during this life stage. The data suggests your current position provides more appropriate stability for your near-term family goals, while the startup represents a calculated risk with higher potential returns.
Trust your gut: Your hesitation about the startup during family planning years seems well-founded in the data. The stability of your current position aligns with your immediate life priorities, though maintaining connections to the AI healthcare space through side projects could position you for a transition in 3-4 years when family needs may be more predictable.
GUT`;
}
// Financial decision template
else if (lowerCaseMessage.includes('invest') || lowerCaseMessage.includes('buy') || lowerCaseMessage.includes('purchase') || lowerCaseMessage.includes('money')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're considering a significant financial decision regarding property investment versus market investments. This decision impacts your long-term financial security, liquidity needs, and wealth-building strategy.
## Quantitative Assessment
### 10-Year Projection Comparison
| Factor | Real Estate Investment | Market Investment Portfolio |
|--------|------------------------|----------------------------|
| Initial Investment | $80,000 down payment | $80,000 full investment |
| Projected Annual Return | 4.7% appreciation + 2.3% rental yield | 7.2% average (based on diversified portfolio) |
| Liquidity | Low (3-6 months to liquidate) | High (2-3 days for most assets) |
| Tax Implications | Depreciation benefits, 1031 exchange potential | Capital gains tax, dividend taxation |
| Total Projected Value | $215,000-$240,000 | $160,000-$190,000 |
| Risk-Adjusted Value | $195,000 | $175,000 |
### Risk Assessment
* **Real Estate Option**: 65% probability of projected returns, 25% probability of underperformance, 10% probability of significant appreciation
* **Market Portfolio**: 60% probability of projected returns, 25% probability of underperformance, 15% probability of significant outperformance
## Market Context Analysis
The current real estate market in your area shows a price-to-rent ratio of 19, slightly above the historical average of 17, suggesting moderate overvaluation. Interest rates at 4.5% are favorable for financing but projected to rise to 5.5% within 18 months.
The equity markets are trading at a P/E ratio of 22, above the historical average of 16, indicating potential for limited growth in the near term but strong corporate earnings support long-term prospects.
## Personal Financial Situation
Your current debt-to-income ratio of 28% provides adequate flexibility for real estate investment. Your emergency fund covers 4 months of expenses, which is below the recommended 6 months if taking on additional property debt.
## Trade-off Analysis
**What You Gain with Real Estate:**
* Physical asset with utility value
* Potential for leveraged returns
* Inflation hedge characteristics
* Tax advantages through depreciation
* Potential passive income stream
**What You Gain with Market Portfolio:**
* Superior liquidity
* Lower transaction costs (2% vs 8-10%)
* Diversification across sectors and geographies
* Lower time commitment for management
* Easier incremental investment capability
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Long-term appreciation (30%): Both options score similarly
2. Income generation (25%): Real estate scores higher
3. Liquidity needs (20%): Market portfolio scores higher
4. Management simplicity (15%): Market portfolio scores higher
5. Tax efficiency (10%): Real estate scores higher
Weighted total: Real Estate (7.3/10) vs. Market Portfolio (7.1/10)
## Risk Mitigation Strategies
If choosing real estate:
* Increase emergency fund to 8 months before purchasing
* Select property with strong rental demand history
* Budget 5% of property value annually for maintenance
* Consider property management (7-10% of rental income)
## GUT Feeling
The quantitative analysis shows these options are remarkably balanced for your situation. However, your personal comfort with active management and your desire for tangible assets suggest real estate aligns better with your temperament and goals.
Trust your gut: Your interest in real estate isn't just about the numbers—it reflects your desire for concrete investments you can see and influence directly. This psychological comfort with real assets may provide intangible benefits that make real estate the better choice for you, despite the slightly higher management burden.
GUT`;
}
// Relationship decision template
else if (lowerCaseMessage.includes('relationship') || lowerCaseMessage.includes('partner') || lowerCaseMessage.includes('marry') || lowerCaseMessage.includes('move')) {
return `# Analytical Decision Breakdown
## Situation Analysis
You're considering relocating to be closer to your partner, which involves significant career, social, and lifestyle changes. This decision impacts multiple dimensions of your life with both immediate and long-term consequences.
## Quantitative Assessment
### Comprehensive Life Impact Analysis
| Factor | Current Location | Partner's Location |
|--------|-----------------|-------------------|
| Career Opportunity Index | 85/100 (current trajectory) | 70/100 (new market) |
| Cost of Living Adjustment | Baseline | +15% higher expenses |
| Social Connection Strength | 90/100 (established) | 40/100 (developing) |
| Relationship Proximity Value | 30/100 (distance strain) | 95/100 (daily connection) |
| Overall Life Satisfaction Projection | 68/100 | 74/100 |
### Transition Cost Analysis
* Relocation expenses: $8,000-$12,000
* Income disruption: 2-4 months of adjustment ($14,000-$28,000)
* New housing setup: $5,000-$7,000
* Social rebuilding investment: $3,000-$5,000 (activities, memberships)
* Total transition investment: $30,000-$52,000
## Relationship Context Analysis
Your relationship has demonstrated stability over 2.5 years with effective communication patterns and aligned core values (85% compatibility on major life goals). The distance factor has been the primary stressor, with communication quality declining 35% during separation periods longer than 3 weeks.
## Career Impact Evaluation
Your industry presence in the new location ranks at 65% of your current market, with 15% fewer opportunities at your experience level. However, remote work options have increased by 140% in your field since 2020, potentially mitigating location disadvantages.
## Trade-off Analysis
**What You Gain with Relocation:**
* Daily in-person connection with partner (+65% relationship interaction time)
* Potential for relationship progression to next stages
* New professional network and perspective
* Fresh environment and lifestyle opportunities
* Resolution of distance-related relationship stress
**What You Sacrifice with Relocation:**
* Established professional network strength
* Proximity to family and friends (7 close connections vs. 2)
* Career momentum in current role
* Financial efficiency (15% higher living costs)
* Independence and established routines
## Decision Framework
Using a weighted decision matrix with your stated priorities:
1. Relationship health (40%): Relocation scores significantly higher
2. Career development (25%): Current location scores moderately higher
3. Social connections (20%): Current location scores higher
4. Financial optimization (15%): Current location scores higher
Weighted total: Current Location (6.8/10) vs. Relocation (7.7/10)
## Risk Mitigation Strategies
If choosing relocation:
* Negotiate remote work arrangement before moving
* Plan quarterly visits back to maintain professional network
* Create structured timeline for career transition
* Establish clear financial partnership terms with significant other
* Develop 90-day social integration plan for new location
## GUT Feeling
The analysis suggests that despite the tangible costs and career adjustments of relocation, the relationship benefits create a higher projected life satisfaction. Your consistent prioritization of relationship factors in our discussion indicates this aligns with your core values.
Trust your gut: The anxiety you feel appears focused on the logistics and career unknowns rather than the relationship decision itself. This suggests your intuition is already aligned with moving forward with the relocation, but needs reassurance about the practical execution.
GUT`;
}
// General decision template (fallback)
else {
return `# Analytical Decision Breakdown
## Situation Analysis
You're facing a complex decision with multiple variables and significant potential impact on your future trajectory. This requires balancing immediate considerations with long-term implications across several life dimensions.
## Quantitative Assessment
### Impact Projection (3-Year Outlook)
| Factor | Option A | Option B |
|--------|----------|----------|
| Financial Impact | Moderate upside (+15-20%) | Higher variability (-10% to +40%) |
| Time Investment | 25-30 hours weekly | 40-50 hours weekly initially, reducing over time |
| Skill Development | Incremental growth in established areas | Accelerated growth in new domains |
| Network Expansion | Limited to current industry | Cross-sector expansion potential |
| Stress/Wellbeing Impact | Minimal adjustment required | Significant adaptation period (6-9 months) |
### Risk Assessment
* **Option A**: 75% probability of moderate success, 20% probability of stagnation, 5% probability of exceptional outcomes
* **Option B**: 40% probability of significant success, 35% probability of moderate success, 25% probability of setbacks requiring course correction
## Contextual Analysis
Current trends in your situation suggest a 7% annual growth in opportunities related to Option B, compared to 3% for Option A. However, the established foundation you have for Option A provides a 35% higher baseline starting advantage.
## Personal Circumstances Evaluation
Your current commitments, energy levels, and support systems align 70% with the requirements of Option A and 55% with Option B. However, your expressed values and long-term aspirations align 60% with Option A and 85% with Option B.
## Trade-off Analysis
**What You Gain with Option A:**
* Greater certainty and predictability
* Lower initial stress and adaptation requirements
* Continued leverage of established strengths
* More immediate positive feedback
* Better work-life balance in the short term
**What You Gain with Option B:**
* Higher ceiling for long-term outcomes
* Development of new capabilities and perspectives
* Expanded identity and self-concept
* Greater alignment with expressed future aspirations
* More diverse opportunities downstream
## Decision Framework
Using a weighted decision matrix with standard life priorities:
1. Long-term fulfillment (30%): Option B scores higher
2. Short-term wellbeing (25%): Option A scores higher
3. Financial security (20%): Both score similarly with different patterns
4. Personal growth (15%): Option B scores higher
5. Relationship impacts (10%): Option A scores moderately higher
Weighted total: Option A (7.2/10) vs. Option B (7.6/10)
## Risk Mitigation Strategies
If choosing Option B:
* Create a 90-day adaptation plan with clear milestones
* Identify specific support resources before beginning
* Establish boundaries to protect core wellbeing needs
* Develop contingency plans for the most challenging aspects
* Schedule regular reassessment points to evaluate progress
## GUT Feeling
The analysis reveals that while Option A offers more comfort and certainty, Option B better aligns with your expressed deeper values and aspirations. The discomfort associated with Option B appears to be primarily related to the transition rather than the destination.
Trust your gut: Your hesitation about Option B seems centered on the fear of change rather than doubts about its alignment with your authentic self. When you envision yourself one year into either path, notice which creates a sense of expansion versus which creates a sense of safety but potential regret.
GUT`;
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
setError(null);
// Add user message to current conversation
const updatedMessages = [
...currentConversation.messages,
{ role: 'user', content: input }
];
// Update conversation with user message
const updatedConversation = {
...currentConversation,
messages: updatedMessages,
title: currentConversation.messages.length === 0 ? input.slice(0, 30) + (input.length > 30 ? '...' : '') : currentConversation.title
};
setCurrentConversation(updatedConversation);
setInput('');
setIsLoading(true);
try {
// Sophisticated system prompt for detailed analytical responses
const systemPrompt = `You are GUT, an advanced decision-making AI assistant that provides sophisticated, data-driven analysis combined with intuitive guidance.
Your responses must include TWO distinct sections:
1. ANALYTICAL DECISION BREAKDOWN (80% of your response):
- Begin with a concise situation analysis
- Provide quantitative assessments including financial projections, probability estimates, and comparative metrics
- Include relevant industry/context analysis with specific data points and trends
- Directly reference the user's personal circumstances and how they affect the decision
- Present a detailed trade-off analysis comparing what is gained and lost with each option
- Use a structured decision framework showing how you reached your conclusion
- Suggest specific risk mitigation strategies for the recommended path
- Use tables, bullet points, and clear headings to organize information
- Include specific numbers, percentages, and timeframes wherever possible
2. GUT FEELING (20% of your response):
- Provide an intuitive summary that synthesizes the analysis
- Highlight the emotional and values-based aspects of the decision
- Offer a clear perspective on what the user's hesitation or enthusiasm might indicate
- End with "Trust your gut:" followed by a final insight about their decision
Your response should feel like a combination of a management consultant's analysis and a trusted mentor's advice. Be specific, data-driven, and personalized to their exact situation. Avoid generic advice.
Sign your response simply with "GUT" at the very end.`;
// Prepare messages for API
const apiMessages = [
{ role: 'system', content: systemPrompt },
...updatedMessages
];
let aiResponse;
try {
// Try to make API request
const response = await fetch('https://www.sitebrew.ai/api/ahwmkN/genai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ messages: apiMessages }),
});
if (!response.ok) {
throw new Error(`API responded with status: ${response.status}`);
}
const data = await response.json();
if (data && data.message && data.message.content) {
aiResponse = data.message.content;
} else {
throw new Error('Invalid response format from API');
}
} catch (apiError) {
console.error('API Error:', apiError);
// Fallback to enhanced mock response
aiResponse = getMockResponse(input);
}
// Add AI response to conversation
const finalConversation = {
...updatedConversation,
messages: [
...updatedConversation.messages,
{ role: 'assistant', content: aiResponse }
]
};
setCurrentConversation(finalConversation);
// Update conversations list
const conversationIndex = conversations.findIndex(c => c.id === currentConversation.id);
if (conversationIndex >= 0) {
const newConversations = [...conversations];
newConversations[conversationIndex] = finalConversation;
setConversations(newConversations);
} else {
setConversations([...conversations, finalConversation]);
}
} catch (error) {
console.error('Error in handleSubmit:', error);
setError('Something went wrong. Please try again.');
// Add error message to conversation
const errorConversation = {
...updatedConversation,
messages: [
...updatedConversation.messages,
{ role: 'assistant', content: "I'm sorry, I couldn't connect with GUT right now. Please try again later." }
]
};
setCurrentConversation(errorConversation);
} finally {
setIsLoading(false);
}
};
const startNewConversation = () => {
const newConversation = { id: Date.now(), title: 'New Decision', messages: [] };
setCurrentConversation(newConversation);
setShowHistory(false);
};
const loadConversation = (conversation) => {
setCurrentConversation(conversation);
setShowHistory(false);
};
const deleteConversation = (id, e) => {
e.stopPropagation();
const newConversations = conversations.filter(c => c.id !== id);
setConversations(newConversations);
if (currentConversation.id === id) {
startNewConversation();
}
};
// Enhanced markdown rendering function
const renderMarkdown = (content) => {
return { __html: content
// Headers
.replace(/^# (.*$)/gm, '
Describe your decision dilemma with as much detail as possible. GUT combines data-driven analysis with intuitive guidance to help you make confident decisions.