import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowLeft, Calendar, Clock, Home, Book, User, Award, Bell, LogOut, Menu, X, ChevronRight, Star, DollarSign, CreditCard, MessageSquare, BarChart2, TrendingUp, TrendingDown, Smile, Frown, Meh, Info, CheckCircle, AlertCircle, Heart, Shield, Settings, FileText, Send, ThumbsUp, ThumbsDown, Flag, Maximize2, Minimize2, Bot, HelpCircle } from 'lucide-react';
// Main App Component
const PurePathApp = () => {
const [currentPage, setCurrentPage] = useState('home');
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [user, setUser] = useState(null);
const [showMenu, setShowMenu] = useState(false);
const [cleanDays, setCleanDays] = useState(0);
const [startDate, setStartDate] = useState(null);
const [blogs, setBlogs] = useState([]);
const [testimonials, setTestimonials] = useState([]);
const [coaches, setCoaches] = useState([]);
const [selectedCoach, setSelectedCoach] = useState(null);
const [selectedDate, setSelectedDate] = useState(null);
const [selectedTime, setSelectedTime] = useState(null);
const [paymentMethod, setPaymentMethod] = useState('');
const [moodData, setMoodData] = useState([]);
const [showNotification, setShowNotification] = useState(false);
const [notification, setNotification] = useState({ message: '', type: 'success' });
const [chatHistory, setChatHistory] = useState([]);
const [showChatbot, setShowChatbot] = useState(false);
const [shareAIData, setShareAIData] = useState(false);
// Chatbot ref to maintain state across renders
const chatbotRef = useRef({
isTyping: false,
currentMessage: '',
context: {},
suggestedResponses: []
});
// Display notification
const displayNotification = (message, type = 'success') => {
setNotification({ message, type });
setShowNotification(true);
setTimeout(() => {
setShowNotification(false);
}, 3000);
};
// Load chat history from local storage when user logs in
useEffect(() => {
if (isLoggedIn && user) {
const savedChatHistory = localStorage.getItem(`chatHistory_${user.email}`);
if (savedChatHistory) {
setChatHistory(JSON.parse(savedChatHistory));
}
const savedShareSetting = localStorage.getItem(`shareAIData_${user.email}`);
if (savedShareSetting !== null) {
setShareAIData(JSON.parse(savedShareSetting));
}
}
}, [isLoggedIn, user]);
// Save chat history to local storage when it changes
useEffect(() => {
if (isLoggedIn && user && chatHistory.length > 0) {
localStorage.setItem(`chatHistory_${user.email}`, JSON.stringify(chatHistory));
}
}, [chatHistory, isLoggedIn, user]);
// Save share AI data preference
useEffect(() => {
if (isLoggedIn && user) {
localStorage.setItem(`shareAIData_${user.email}`, JSON.stringify(shareAIData));
}
}, [shareAIData, isLoggedIn, user]);
// Update chatbot context when relevant data changes
useEffect(() => {
if (isLoggedIn) {
chatbotRef.current.context = {
currentPage,
cleanDays,
moodData: moodData.slice(0, 7), // Last 7 days of mood data
recentBlogs: blogs.slice(0, 3), // Recent blog posts
user
};
}
}, [currentPage, cleanDays, moodData, blogs, isLoggedIn, user]);
// Simulate fetching data
useEffect(() => {
// Mock data
const mockBlogs = [
{ id: 1, title: "Finding Strength in Community", category: "Support", date: "2023-05-15", content: "Building a support network is crucial in overcoming addiction...", image: "https://images.unsplash.com/photo-1529156069898-49953e39b3ac?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" },
{ id: 2, title: "The Science Behind Addiction", category: "Education", date: "2023-05-10", content: "Understanding the neurological aspects of addiction can help in recovery...", image: "https://images.unsplash.com/photo-1532938911079-1b06ac7ceec7?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" },
{ id: 3, title: "Daily Devotional: Renewal", category: "Spiritual", date: "2023-05-05", content: "Today's reflection focuses on the concept of renewal and how it applies to our journey...", image: "https://images.unsplash.com/photo-1504805572947-34fad45aed93?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" },
];
const mockTestimonials = [
{ id: 1, name: "John D.", rating: 5, text: "The coaching sessions have been transformative. I've been clean for 60 days now.", date: "2023-04-20" },
{ id: 2, name: "Sarah M.", rating: 4, text: "The app's tracking feature keeps me accountable. The community support is amazing.", date: "2023-04-15" },
{ id: 3, name: "Anonymous", rating: 5, text: "I was skeptical at first, but the personalized approach has made all the difference.", date: "2023-04-10" },
];
const mockCoaches = [
{ id: 1, name: "Dr. Michael Johnson", specialty: "Addiction Recovery", experience: "15 years", rate: 75, image: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", availability: ["Monday", "Wednesday", "Friday"] },
{ id: 2, name: "Sarah Williams", specialty: "Spiritual Counseling", experience: "8 years", rate: 60, image: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", availability: ["Tuesday", "Thursday", "Saturday"] },
{ id: 3, name: "Admin (You)", specialty: "Recovery Specialist", experience: "10 years", rate: 80, image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", availability: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] },
];
setBlogs(mockBlogs);
setTestimonials(mockTestimonials);
setCoaches(mockCoaches);
// Check if user has a clean streak stored
const savedStartDate = localStorage.getItem('cleanStartDate');
if (savedStartDate) {
const start = new Date(savedStartDate);
setStartDate(start);
const today = new Date();
const diffTime = Math.abs(today - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
setCleanDays(diffDays);
}
// Load mood data from localStorage
const savedMoodData = localStorage.getItem('moodData');
if (savedMoodData) {
setMoodData(JSON.parse(savedMoodData));
} else {
// Generate some mock mood data if none exists
const mockMoodData = generateMockMoodData(30);
setMoodData(mockMoodData);
localStorage.setItem('moodData', JSON.stringify(mockMoodData));
}
}, []);
// Generate mock mood data for the past n days
const generateMockMoodData = (days) => {
const data = [];
const today = new Date();
for (let i = days - 1; i >= 0; i--) {
const date = new Date();
date.setDate(today.getDate() - i);
// Generate random mood between 1-5
const mood = Math.floor(Math.random() * 5) + 1;
// Generate random notes
const notes = [
"Feeling strong today",
"Struggled a bit but stayed clean",
"Had a great coaching session",
"Meditation helped a lot",
"Difficult day but made it through",
"Feeling motivated",
"Temptations were strong today"
];
data.push({
date: date.toISOString().split('T')[0],
mood,
notes: notes[Math.floor(Math.random() * notes.length)],
});
}
return data;
};
// Update clean days counter
useEffect(() => {
if (startDate) {
const interval = setInterval(() => {
const today = new Date();
const diffTime = Math.abs(today - startDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
setCleanDays(diffDays);
}, 86400000); // Update once per day
return () => clearInterval(interval);
}
}, [startDate]);
// Handle login
const handleLogin = (userData) => {
setUser(userData);
setIsLoggedIn(true);
setCurrentPage('home');
displayNotification(`Welcome back, ${userData.name}!`, 'success');
// Check if user has a clean streak
if (!startDate) {
const newStartDate = new Date();
setStartDate(newStartDate);
localStorage.setItem('cleanStartDate', newStartDate.toISOString());
setCleanDays(0);
}
// Add welcome message from chatbot
setTimeout(() => {
addChatbotMessage("Welcome back! I'm here to support your journey. How can I help you today?");
}, 1000);
};
// Handle logout
const handleLogout = () => {
setUser(null);
setIsLoggedIn(false);
setCurrentPage('login');
setShowMenu(false);
setChatHistory([]);
setShowChatbot(false);
displayNotification('You have been logged out', 'info');
};
// Reset clean streak
const resetCleanStreak = () => {
const newStartDate = new Date();
setStartDate(newStartDate);
localStorage.setItem('cleanStartDate', newStartDate.toISOString());
setCleanDays(0);
displayNotification('Your clean streak has been reset', 'info');
// Add supportive message from chatbot
if (showChatbot) {
addChatbotMessage("I noticed you've reset your clean streak. Remember, every journey has setbacks, and each new day is an opportunity to start fresh. Would you like some tips on how to stay motivated?");
}
};
// Log mood
const logMood = (mood, notes) => {
const today = new Date().toISOString().split('T')[0];
// Check if we already have a mood for today
const updatedMoodData = [...moodData];
const todayIndex = updatedMoodData.findIndex(item => item.date === today);
if (todayIndex >= 0) {
// Update existing entry
updatedMoodData[todayIndex] = { date: today, mood, notes };
displayNotification('Your mood has been updated', 'success');
} else {
// Add new entry
updatedMoodData.push({ date: today, mood, notes });
displayNotification('Your mood has been logged', 'success');
}
// Sort by date (newest first)
updatedMoodData.sort((a, b) => new Date(b.date) - new Date(a.date));
setMoodData(updatedMoodData);
localStorage.setItem('moodData', JSON.stringify(updatedMoodData));
// Add chatbot response based on mood
if (showChatbot) {
if (mood <= 2) {
addChatbotMessage("I notice you're not feeling great today. Would you like some suggestions to help improve your mood?");
} else if (mood >= 4) {
addChatbotMessage("Great to see you're feeling good today! Would you like to explore some activities to maintain this positive momentum?");
}
}
};
// Book appointment
const bookAppointment = () => {
if (selectedCoach && selectedDate && selectedTime && paymentMethod) {
// In a real app, this would process the payment and book the appointment
displayNotification(`Appointment booked with ${selectedCoach.name}`, 'success');
setCurrentPage('home');
setSelectedCoach(null);
setSelectedDate(null);
setSelectedTime(null);
setPaymentMethod('');
// Add chatbot message about the appointment
if (showChatbot) {
addChatbotMessage(`I see you've booked a session with ${selectedCoach.name}. That's a great step! Would you like some tips on how to prepare for your coaching session?`);
}
} else {
displayNotification('Please complete all booking details', 'error');
}
};
// Submit review
const submitReview = (coachId, rating, text) => {
// In a real app, this would send the review to the backend
displayNotification('Thank you for your review!', 'success');
setCurrentPage('home');
};
// Add a message from the chatbot
const addChatbotMessage = (message, suggestions = []) => {
chatbotRef.current.isTyping = true;
setChatHistory(prev => [...prev, { type: 'typing', sender: 'bot' }]);
// Simulate typing delay
setTimeout(() => {
setChatHistory(prev => {
const newHistory = [...prev];
const typingIndex = newHistory.findIndex(msg => msg.type === 'typing');
if (typingIndex !== -1) {
newHistory.splice(typingIndex, 1);
}
return [...newHistory, {
type: 'text',
sender: 'bot',
content: message,
timestamp: new Date().toISOString(),
suggestions,
rated: false
}];
});
chatbotRef.current.isTyping = false;
}, 1500);
};
// Handle user message to chatbot
const handleSendMessage = (message) => {
if (!message.trim()) return;
// Add user message to chat history
setChatHistory(prev => [...prev, {
type: 'text',
sender: 'user',
content: message,
timestamp: new Date().toISOString()
}]);
// Process the message and generate a response
processUserMessage(message);
};
// Process user message and generate AI response
const processUserMessage = (message) => {
const lowerMessage = message.toLowerCase();
const context = chatbotRef.current.context;
// Simple keyword-based responses
if (lowerMessage.includes('help') || lowerMessage.includes('support')) {
addChatbotMessage(
"I'm here to help! You can ask me about coping strategies, recovery resources, or get personalized advice based on your journey.",
["Tell me about coping strategies", "How to handle urges?", "Recommend resources"]
);
}
else if (lowerMessage.includes('urge') || lowerMessage.includes('craving') || lowerMessage.includes('temptation')) {
addChatbotMessage(
"When experiencing urges, try the 5-minute rule: acknowledge the urge and commit to waiting 5 minutes before acting on it. During this time, distract yourself with a different activity. Often, the urge will pass or diminish. Would you like more strategies?",
["More urge strategies", "Distraction techniques", "Emergency contacts"]
);
}
else if (lowerMessage.includes('mood') || lowerMessage.includes('feeling')) {
// Personalized response based on mood data
const recentMoods = context.moodData || [];
if (recentMoods.length > 0) {
const latestMood = recentMoods[0];
if (latestMood.mood <= 2) {
addChatbotMessage(
`I see you've been feeling down recently. Remember that it's normal to have difficult days. Some activities that might help: gentle exercise, calling a supportive friend, or practicing mindfulness for 10 minutes.`,
["Mindfulness exercises", "Contact support", "Self-care tips"]
);
} else if (latestMood.mood >= 4) {
addChatbotMessage(
`It's great to see you've been in a positive mood lately! This is a good time to build on your momentum. Consider setting a small goal for today or reaching out to support someone else on their journey.`,
["Set a goal", "Help others", "Maintain momentum"]
);
} else {
addChatbotMessage(
`Based on your recent mood entries, you seem to be doing okay. Remember to take time for self-care and celebrate your progress, no matter how small.`,
["Self-care ideas", "Celebrate progress", "Daily affirmations"]
);
}
} else {
addChatbotMessage(
"How are you feeling today? Tracking your mood can help identify patterns and triggers. Would you like to log your mood now?",
["Log my mood", "Mood tracking benefits", "Not now"]
);
}
}
else if (lowerMessage.includes('streak') || lowerMessage.includes('clean') || lowerMessage.includes('sober')) {
// Response based on clean streak
if (context.cleanDays === 0) {
addChatbotMessage(
"Every journey begins with a single step. Today is the first day of your new path, and I'm here to support you every step of the way. Would you like some tips for getting through the first week?",
["First week tips", "Daily affirmations", "Emergency contacts"]
);
} else if (context.cleanDays < 7) {
addChatbotMessage(
`You've been clean for ${context.cleanDays} days - that's fantastic! The first week can be challenging, but you're making great progress. Focus on one day at a time and be proud of each clean day.`,
["Dealing with withdrawal", "Sleep tips", "Hydration importance"]
);
} else if (context.cleanDays < 30) {
addChatbotMessage(
`${context.cleanDays} days clean is a significant achievement! You're building new habits and rewiring your brain. The urges may still come, but they'll gradually become less intense and less frequent.`,
["Building new habits", "Neuroplasticity", "Reward yourself"]
);
} else {
addChatbotMessage(
`Congratulations on ${context.cleanDays} days clean! This is a remarkable achievement. You've proven your strength and commitment. Remember to celebrate these milestones and reflect on how far you've come.`,
["Long-term strategies", "Share your story", "Help others"]
);
}
}
else if (lowerMessage.includes('resource') || lowerMessage.includes('article') || lowerMessage.includes('read')) {
// Recommend resources based on context
const recommendedBlogs = context.recentBlogs || [];
if (recommendedBlogs.length > 0) {
const blog = recommendedBlogs[Math.floor(Math.random() * recommendedBlogs.length)];
addChatbotMessage(
`I'd recommend reading "${blog.title}" from our blog. It covers important aspects of recovery and might provide valuable insights for your journey.`,
["Show me the article", "More recommendations", "Not interested"]
);
} else {
addChatbotMessage(
"We have several resources that might help you. Our blog covers topics like building support networks, understanding addiction science, and spiritual aspects of recovery. Would you like to explore these?",
["Show me the blog", "Recommend a book", "External resources"]
);
}
}
else if (lowerMessage.includes('coach') || lowerMessage.includes('therapy') || lowerMessage.includes('counseling')) {
addChatbotMessage(
"Working with a coach or counselor can provide personalized guidance and accountability. Our certified coaches specialize in addiction recovery and can help you develop strategies tailored to your specific needs.",
["View coaches", "Benefits of coaching", "What to expect"]
);
}
else if (lowerMessage.includes('thank')) {
addChatbotMessage(
"You're welcome! I'm here to support you whenever you need it. Is there anything else I can help with today?",
["Recovery tips", "Mood tracking", "Resources"]
);
}
// Context-aware responses based on current page
else if (context.currentPage === 'tracker') {
addChatbotMessage(
"I see you're on the tracker page. Tracking your clean time and mood can provide valuable insights into your recovery journey. Would you like some tips on how to use these tools effectively?",
["Tracking benefits", "Identify patterns", "Set milestones"]
);
}
else if (context.currentPage === 'coaching') {
addChatbotMessage(
"Looking for a coach? Working with a professional can accelerate your progress and provide personalized guidance. Our coaches have extensive experience in addiction recovery and can help you develop effective strategies.",
["Coach selection tips", "Prepare for coaching", "Coaching benefits"]
);
}
else if (context.currentPage === 'blog') {
addChatbotMessage(
"Our blog contains valuable resources and insights for your recovery journey. Reading about others' experiences and evidence-based strategies can provide new perspectives and tools for your own path.",
["Recommended articles", "Latest research", "Success stories"]
);
}
else {
// Default response
addChatbotMessage(
"I'm here to support your recovery journey. You can ask me about coping strategies, resources, or get personalized advice based on your progress. How can I assist you today?",
["Coping strategies", "Recovery resources", "Track my progress"]
);
}
};
// Handle suggestion click
const handleSuggestionClick = (suggestion) => {
// Add the suggestion as a user message
setChatHistory(prev => [...prev, {
type: 'text',
sender: 'user',
content: suggestion,
timestamp: new Date().toISOString()
}]);
// Process the suggestion
processUserMessage(suggestion);
};
// Handle rating a bot message
const handleRateMessage = (index, isHelpful) => {
setChatHistory(prev => {
const newHistory = [...prev];
if (newHistory[index] && newHistory[index].sender === 'bot') {
newHistory[index] = {
...newHistory[index],
rated: true,
helpful: isHelpful
};
// If sharing is enabled, this would send the rating to the backend
if (shareAIData && isLoggedIn) {
console.log('Sending rating to backend:', {
messageId: index,
message: newHistory[index].content,
helpful: isHelpful,
userId: user.email,
timestamp: new Date().toISOString()
});
}
}
return newHistory;
});
displayNotification(isHelpful ? 'Thank you for your feedback!' : 'We\'ll work on improving this response', 'info');
};
// Handle reporting incorrect advice
const handleReportMessage = (index) => {
setChatHistory(prev => {
const newHistory = [...prev];
if (newHistory[index] && newHistory[index].sender === 'bot') {
newHistory[index] = {
...newHistory[index],
reported: true
};
// If sharing is enabled, this would send the report to the backend
if (shareAIData && isLoggedIn) {
console.log('Sending report to backend:', {
messageId: index,
message: newHistory[index].content,
userId: user.email,
timestamp: new Date().toISOString()
});
}
}
return newHistory;
});
displayNotification('Thank you for reporting this response. We\'ll review it to improve our AI.', 'info');
// Add follow-up message from bot
addChatbotMessage("I apologize for the incorrect information. Thank you for helping me improve. Is there something else I can help you with?");
};
// Toggle share AI data setting
const toggleShareAIData = () => {
setShareAIData(prev => !prev);
displayNotification(
shareAIData
? 'You\'ve opted out of sharing anonymous data'
: 'Thank you for helping improve our AI by sharing anonymous data',
'info'
);
};
// Render different pages based on currentPage state
const renderPage = () => {
if (!isLoggedIn && currentPage !== 'login' && currentPage !== 'signup' && currentPage !== 'reset-password') {
return ;
}
switch (currentPage) {
case 'home':
return ;
case 'tracker':
return ;
case 'blog':
return ;
case 'blog-detail':
return b.id === parseInt(currentPage.split('-')[2]))} setCurrentPage={setCurrentPage} />;
case 'coaching':
return ;
case 'booking':
return ;
case 'payment':
return ;
case 'testimonials':
return ;
case 'profile':
return ;
case 'login':
return ;
case 'signup':
return ;
case 'reset-password':
return ;
case 'write-review':
return ;
default:
return ;
}
};
// Toggle side menu
const toggleMenu = () => {
setShowMenu(!showMenu);
};
// Toggle chatbot
const toggleChatbot = () => {
setShowChatbot(prev => !prev);
// If opening the chatbot and no messages yet, add welcome message
if (!showChatbot && chatHistory.length === 0) {
addChatbotMessage("Hi there! I'm your PurePath assistant. I can provide support, resources, and personalized advice for your recovery journey. How can I help you today?",
["Tell me about recovery", "I'm having urges", "Recommend resources"]
);
}
};
return (
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Understanding the Journey
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Focus on daily progress
Build a support network
Practice mindfulness
Identify and avoid triggers
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
"Recovery is not a race. You don't have to feel guilty if it takes you longer than you thought it would."