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 (
{/* Header */}
{currentPage !== 'home' && isLoggedIn ? ( ) : ( )}

PurePath

{isLoggedIn && (
)}
{/* Side Menu */} {showMenu && isLoggedIn && (
e.stopPropagation()} >

PurePath

Your journey to freedom

)} {/* Main Content */}
{renderPage()}
{/* Bottom Navigation */} {isLoggedIn && ( )} {/* Chatbot Button */} {isLoggedIn && ( )} {/* Chatbot Interface */} {isLoggedIn && showChatbot && (
{/* Chatbot Header */}

PurePath Assistant

AI-powered support

{/* Chat Messages */}
{chatHistory.map((message, index) => (
{message.type === 'typing' ? (
) : (

{message.content}

{/* Suggestions */} {message.sender === 'bot' && message.suggestions && message.suggestions.length > 0 && (
{message.suggestions.map((suggestion, i) => ( ))}
)} {/* Rating and Report Options */} {message.sender === 'bot' && !message.rated && !message.reported && (
)} {/* Rated Message */} {message.sender === 'bot' && message.rated && (
{message.helpful ? 'Thanks for your feedback!' : 'Thanks for your feedback. We\'ll improve this response.'}
)} {/* Reported Message */} {message.sender === 'bot' && message.reported && (
This response has been reported. Thank you for helping us improve.
)}
)}
))} {chatHistory.length === 0 && (

PurePath Assistant

I'm here to support your recovery journey with personalized advice and resources.

)}
{/* Chat Input */}
{ e.preventDefault(); const input = e.target.elements.message; handleSendMessage(input.value); input.value = ''; }} className="flex items-center" >
{shareAIData ? 'Anonymous data sharing is enabled' : 'Anonymous data sharing is disabled'}
)} {/* Notification */} {showNotification && (
{notification.type === 'success' && } {notification.type === 'error' && } {notification.type === 'info' && } {notification.message}
)}
); }; // Home Page Component const HomePage = ({ cleanDays, resetCleanStreak, blogs, setCurrentPage, moodData, logMood }) => { // Get today's mood if logged const today = new Date().toISOString().split('T')[0]; const todayMood = moodData.find(item => item.date === today); return (
{/* Welcome Message */}

Welcome Back

Continue your journey to freedom

{/* Clean Streak Card */}

Your Clean Streak

Every day is a victory

{cleanDays}

Days Clean

{/* Today's Mood */}

How are you feeling today?

{todayMood ? (
{todayMood.mood === 1 && } {todayMood.mood === 2 && } {todayMood.mood === 3 && } {todayMood.mood === 4 && } {todayMood.mood === 5 && }

"{todayMood.notes}"

) : (

You haven't logged your mood today

)}
{/* Quick Actions */}

Quick Actions

{/* Recent Blog Posts */}

Recent Articles

{blogs.map(blog => (
setCurrentPage(`blog-detail-${blog.id}`)} >
{blog.title}
{blog.category}

{blog.title}

{blog.content}

{blog.date} Read More
))}
{/* Motivational Quote */}

"The journey of a thousand miles begins with a single step. Every day clean is a victory worth celebrating."

); }; // Tracker Page Component with Mood Tracking const TrackerPage = ({ cleanDays, startDate, resetCleanStreak, moodData, logMood }) => { const [showMoodLog, setShowMoodLog] = useState(false); const [selectedMood, setSelectedMood] = useState(3); const [moodNotes, setMoodNotes] = useState(''); const [activeTab, setActiveTab] = useState('streak'); // Calculate milestone dates const getMilestoneDate = (days) => { if (!startDate) return null; const date = new Date(startDate); date.setDate(date.getDate() + days); return date.toLocaleDateString(); }; // Define milestones const milestones = [ { days: 1, label: "First Day", achieved: cleanDays >= 1 }, { days: 7, label: "One Week", achieved: cleanDays >= 7 }, { days: 30, label: "One Month", achieved: cleanDays >= 30 }, { days: 90, label: "Three Months", achieved: cleanDays >= 90 }, { days: 180, label: "Six Months", achieved: cleanDays >= 180 }, { days: 365, label: "One Year", achieved: cleanDays >= 365 }, ]; // Get today's mood if logged const today = new Date().toISOString().split('T')[0]; const todayMood = moodData.find(item => item.date === today); // Initialize mood form with today's values if they exist useEffect(() => { if (todayMood) { setSelectedMood(todayMood.mood); setMoodNotes(todayMood.notes || ''); } else { setSelectedMood(3); setMoodNotes(''); } }, [todayMood]); // Handle mood submission const handleMoodSubmit = () => { logMood(selectedMood, moodNotes); setShowMoodLog(false); }; // Calculate mood statistics const calculateMoodStats = () => { if (moodData.length === 0) return { average: 0, distribution: [] }; // Calculate average mood const sum = moodData.reduce((acc, item) => acc + item.mood, 0); const average = sum / moodData.length; // Calculate distribution const distribution = [0, 0, 0, 0, 0]; // For moods 1-5 moodData.forEach(item => { distribution[item.mood - 1]++; }); // Calculate percentages const distributionPercentages = distribution.map(count => Math.round((count / moodData.length) * 100) ); // Find most common mood let maxIndex = 0; for (let i = 1; i < distribution.length; i++) { if (distribution[i] > distribution[maxIndex]) { maxIndex = i; } } const mostCommonMood = maxIndex + 1; // Calculate 7-day trend const last7Days = moodData.slice(0, 7).reverse(); const trend = last7Days.length > 1 ? (last7Days[last7Days.length - 1].mood - last7Days[0].mood) : 0; return { average: average.toFixed(1), distribution: distributionPercentages, mostCommonMood, trend }; }; const moodStats = calculateMoodStats(); // Format date for display const formatDate = (dateString) => { const date = new Date(dateString); return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); }; // Render mood emoji based on rating const renderMoodEmoji = (mood) => { switch (mood) { case 1: return ; case 2: return ; case 3: return ; case 4: return ; case 5: return ; default: return null; } }; // Render mood color based on rating const getMoodColor = (mood) => { switch (mood) { case 1: return 'bg-red-500'; case 2: return 'bg-orange-500'; case 3: return 'bg-yellow-500'; case 4: return 'bg-lime-500'; case 5: return 'bg-green-500'; default: return 'bg-gray-300'; } }; // Render mood chart const renderMoodChart = () => { const last14Days = [...moodData].slice(0, 14).reverse(); return (
{last14Days.map((item, index) => (
{formatDate(item.date)}
))}
); }; return (
{/* Tabs */}
{activeTab === 'streak' ? ( <>

Clean Time Tracker

{/* Main Counter */}

You've been clean for

{cleanDays} days
{startDate && (

Since {startDate.toLocaleDateString()}

)}
{/* Milestones */}

Milestones

{milestones.map((milestone, index) => (
{milestone.achieved ? '✓' : milestone.days}

{milestone.label}

{milestone.achieved ? `Achieved on ${getMilestoneDate(milestone.days)}` : `Expected on ${getMilestoneDate(milestone.days)}`}

))}
{/* Motivational Section */}

Keep Going!

Every day is a new victory. Remember why you started this journey and stay committed to your goals.

) : ( <>

Mood Tracker

{/* Mood Chart */}

Your Mood Trends

{moodData.length > 0 ? ( <> {renderMoodChart()}
Very Low
Neutral
Very Good
) : (

No mood data available yet

)}
{/* Mood Insights */}

Mood Insights

Average Mood

{moodStats.average} / 5

Most Common

{renderMoodEmoji(moodStats.mostCommonMood)} {moodStats.mostCommonMood === 1 ? 'Very Low' : moodStats.mostCommonMood === 2 ? 'Low' : moodStats.mostCommonMood === 3 ? 'Neutral' : moodStats.mostCommonMood === 4 ? 'Good' : 'Very Good'}

7-Day Trend

{moodStats.trend > 0 ? ( ) : moodStats.trend < 0 ? ( ) : ( )} {moodStats.trend > 0 ? 'Improving' : moodStats.trend < 0 ? 'Declining' : 'Stable'}

Entries

{moodData.length}

{/* Mood Distribution */}

Mood Distribution

{[5, 4, 3, 2, 1].map(level => (
{renderMoodEmoji(level)}
{moodStats.distribution[level - 1]}%
))}
{/* Recent Mood Entries */}

Recent Entries

{moodData.slice(0, 5).map((item, index) => (
{renderMoodEmoji(item.mood)}

{item.notes || 'No notes'}

{formatDate(item.date)}

))}
{/* Correlations */}

Insights & Correlations

Coaching Impact

Your mood tends to improve after coaching sessions. Consider scheduling regular sessions for better emotional well-being.

Weekly Patterns

Your mood is typically higher on weekends. Consider incorporating more weekend activities into your weekday routine.

Clean Streak Correlation

Your mood has improved by 25% since starting your clean streak. Keep going!

)} {/* Mood Logging Modal */} {showMoodLog && (

How are you feeling today?

{/* Mood Selection */}
{[1, 2, 3, 4, 5].map(mood => ( ))}
)}
); }; // Blog Page Component const BlogPage = ({ blogs, setCurrentPage }) => { const [activeCategory, setActiveCategory] = useState('All'); const categories = ['All', 'Support', 'Education', 'Spiritual']; const filteredBlogs = activeCategory === 'All' ? blogs : blogs.filter(blog => blog.category === activeCategory); return (

Blog & Resources

{/* Categories */}
{categories.map(category => ( ))}
{/* Blog List */}
{filteredBlogs.map(blog => (
setCurrentPage(`blog-detail-${blog.id}`)} >
{blog.title}
{blog.category} {blog.date}

{blog.title}

{blog.content}

))}
); }; // Blog Detail Page Component const BlogDetailPage = ({ blog, setCurrentPage }) => { if (!blog) { return (

Blog post not found

); } return (
{blog.title}
{blog.category} {blog.date}

{blog.title}

{blog.content}

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."

); }; // Coaching Page Component const CoachingPage = ({ coaches, setSelectedCoach, setCurrentPage }) => { return (

Book a Coaching Session

Our certified coaches are here to provide personalized guidance on your journey to freedom.

{/* Coaches List */}
{coaches.map(coach => (
{coach.name}

{coach.name}

{coach.specialty}

{coach.experience} experience

${coach.rate}

per session

Available on: {coach.availability.join(', ')}

))}
); }; // Booking Page Component const BookingPage = ({ coach, setSelectedDate, setSelectedTime, selectedDate, selectedTime, setCurrentPage }) => { const [currentMonth, setCurrentMonth] = useState(new Date()); // Generate calendar days const generateCalendarDays = () => { const year = currentMonth.getFullYear(); const month = currentMonth.getMonth(); const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const daysInMonth = lastDay.getDate(); const startingDayOfWeek = firstDay.getDay(); const days = []; // Add empty cells for days before the first day of the month for (let i = 0; i < startingDayOfWeek; i++) { days.push(null); } // Add days of the month for (let i = 1; i <= daysInMonth; i++) { const date = new Date(year, month, i); const dayOfWeek = date.getDay(); // Check if this day is available (coach works on this day) const dayName = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek]; const isAvailable = coach.availability.includes(dayName); days.push({ day: i, date, isAvailable, }); } return days; }; // Generate time slots const generateTimeSlots = () => { const slots = []; for (let hour = 9; hour <= 17; hour++) { slots.push(`${hour}:00`); if (hour < 17) { slots.push(`${hour}:30`); } } return slots; }; const calendarDays = generateCalendarDays(); const timeSlots = generateTimeSlots(); // Format date for display const formatDate = (date) => { if (!date) return ''; return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }); }; // Navigate to previous month const prevMonth = () => { setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1)); }; // Navigate to next month const nextMonth = () => { setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1)); }; return (

Book a Session with {coach.name}

{/* Coach Info */}
{coach.name}

{coach.name}

${coach.rate} per session

{/* Calendar */}

{currentMonth.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}

{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map(day => (
{day}
))}
{calendarDays.map((day, index) => (
{day && ( )}
))}
{/* Time Slots */} {selectedDate && (

Select a Time for {formatDate(selectedDate ? new Date(selectedDate) : null)}

{timeSlots.map(time => ( ))}
)} {/* Continue Button */}
); }; // Payment Page Component const PaymentPage = ({ coach, selectedDate, selectedTime, setPaymentMethod, paymentMethod, bookAppointment, setCurrentPage }) => { const formatDate = (dateString) => { if (!dateString) return ''; const date = new Date(dateString); return date.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' }); }; return (

Payment

{/* Booking Summary */}

Booking Summary

Coach: {coach.name}
Date: {formatDate(selectedDate)}
Time: {selectedTime}
Duration: 60 minutes
Total: ${coach.rate}
{/* Payment Methods */}

Select Payment Method

{/* Payment Form */} {paymentMethod === 'credit-card' && (

Card Details

)} {paymentMethod === 'mpesa' && (

M-Pesa Details

)} {paymentMethod === 'paypal' && (

PayPal

You will be redirected to PayPal to complete your payment.

)} {/* Pay Button */}

By proceeding, you agree to our Terms of Service and Privacy Policy.

); }; // Testimonials Page Component const TestimonialsPage = ({ testimonials, setCurrentPage }) => { return (

Client Testimonials

Read about the experiences of others on their journey to freedom.

{/* Testimonials List */}
{testimonials.map(testimonial => (
{testimonial.name.charAt(0)}

{testimonial.name}

{testimonial.date}

{[...Array(5)].map((_, i) => ( ))}

"{testimonial.text}"

))}
{/* Write Review Button */}
); }; // Write Review Page Component const WriteReviewPage = ({ coachId, submitReview, setCurrentPage }) => { const [rating, setRating] = useState(0); const [reviewText, setReviewText] = useState(''); const [isAnonymous, setIsAnonymous] = useState(false); return (

Write a Review

Rate your experience

{[...Array(5)].map((_, i) => ( ))}
setIsAnonymous(!isAnonymous)} className="w-4 h-4 text-blue-500 border-slate-300 rounded focus:ring-blue-500" />
); }; // Profile Page Component const ProfilePage = ({ user, handleLogout, setCurrentPage, shareAIData, toggleShareAIData }) => { return (

Profile

{/* User Info */}
{user?.name?.charAt(0) || 'U'}

{user?.name || 'User'}

{user?.email || 'user@example.com'}

{/* Account Settings */}

Account Settings

{/* AI Assistant Settings */}

AI Assistant Settings

Share Anonymous Data

Help improve our AI by sharing anonymous conversation data

{/* App Settings */}

App Settings

) : ( )}

PurePath

{isLoggedIn && (
)} {/* Side Menu */} {showMenu && isLoggedIn && (
e.stopPropagation()} >

PurePath

Your journey to freedom

)} {/* Main Content */}
{renderPage()}
{/* Bottom Navigation */} {isLoggedIn && ( )} {/* Notification */} {showNotification && (
{notification.type === 'success' && } {notification.type === 'error' && } {notification.type === 'info' && } {notification.message}
)}
); }; // Home Page Component const HomePage = ({ cleanDays, resetCleanStreak, blogs, setCurrentPage, moodData, logMood }) => { // Get today's mood if logged const today = new Date().toISOString().split('T')[0]; const todayMood = moodData.find(item => item.date === today); return (
{/* Welcome Message */}

Welcome Back

Continue your journey to freedom

{/* Clean Streak Card */}

Your Clean Streak

Every day is a victory

{cleanDays}

Days Clean

{/* Today's Mood */}

How are you feeling today?

{todayMood ? (
{todayMood.mood === 1 && } {todayMood.mood === 2 && } {todayMood.mood === 3 && } {todayMood.mood === 4 && } {todayMood.mood === 5 && }

"{todayMood.notes}"

) : (

You haven't logged your mood today

)}
{/* Quick Actions */}

Quick Actions

{/* Recent Blog Posts */}

Recent Articles

{blogs.map(blog => (
setCurrentPage(`blog-detail-${blog.id}`)} >
{blog.title}
{blog.category}

{blog.title}

{blog.content}

{blog.date} Read More
))}
{/* Motivational Quote */}

"The journey of a thousand miles begins with a single step. Every day clean is a victory worth celebrating."

); } // TrackerPage, BlogPage, BlogDetailPage, CoachingPage, BookingPage, PaymentPage, TestimonialsPage, WriteReviewPage, ProfilePage, LoginPage, SignupPage, ResetPasswordPage, and the style block and export remain the same -- see above for full code. const style = document.createElement('style'); style.textContent = ` @keyframes slide-in { 0% { transform: translateX(-100%); } 100% { transform: translateX(0); } } @keyframes slide-up { 0% { transform: translateY(20px); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } .animate-slide-in { animation: slide-in 0.3s ease-out forwards; } .animate-slide-up { animation: slide-up 0.3s ease-out forwards; } .animate-fade-in { animation: fade-in 0.3s ease-out forwards; } .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; } .scrollbar-hide::-webkit-scrollbar { display: none; } `; document.head.appendChild(style); export default PurePathApp;