import React, { useState, useEffect, useRef } from 'react'; import { authManager } from '../utils/auth'; import { imageHandler } from '../utils/imageHandler'; const Community = ({ onNavigate }) => { const [posts, setPosts] = useState([]); const [newPost, setNewPost] = useState(''); const [currentUser, setCurrentUser] = useState(null); const [activeTab, setActiveTab] = useState('feed'); const [leaderboard, setLeaderboard] = useState([]); const [communityStats, setCommunityStats] = useState({}); const [isLoading, setIsLoading] = useState(false); const [selectedImage, setSelectedImage] = useState(null); const [selectedLocation, setSelectedLocation] = useState(''); const [postType, setPostType] = useState('general'); const fileInputRef = useRef(null); useEffect(() => { loadCommunityData(); const user = authManager.getCurrentUser(); setCurrentUser(user); }, []); const loadCommunityData = () => { // Load community posts from localStorage or generate demo data const savedPosts = localStorage.getItem('ecospire_community_posts'); if (savedPosts) { setPosts(JSON.parse(savedPosts)); } else { generateInitialPosts(); } // Load leaderboard setLeaderboard(authManager.getLeaderboard()); // Generate community stats setCommunityStats({ totalMembers: 12847 + Math.floor(Math.random() * 100), waterTests: 45231 + Math.floor(Math.random() * 50), speciesIdentified: 28956 + Math.floor(Math.random() * 20), co2Saved: 156789 + Math.floor(Math.random() * 100), activeToday: 1247 + Math.floor(Math.random() * 50), postsToday: 89 + Math.floor(Math.random() * 10) }); }; const generateInitialPosts = () => { const initialPosts = [ { id: 1, author: 'EcoExplorer', avatar: '๐ŸŒฑ', timestamp: Date.now() - 2 * 60 * 60 * 1000, // 2 hours ago content: 'Just completed my first water quality test using AquaLens! The results were fascinating - found some concerning nitrate levels in our local stream. Time to take action! ๐Ÿ’ง', likes: 12, comments: [ { author: 'WaterGuardian', content: 'Great work! Have you contacted local authorities about the nitrate levels?', timestamp: Date.now() - 1 * 60 * 60 * 1000 }, { author: 'EcoNewbie', content: 'How accurate is AquaLens? Thinking of trying it myself!', timestamp: Date.now() - 30 * 60 * 1000 } ], type: 'water_test', location: 'Riverside Park Stream', image: { url: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgZmlsbD0iIzg3Q0VFQiIvPjx0ZXh0IHg9IjIwMCIgeT0iMTUwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTgiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj7wn5KnIFdhdGVyIFRlc3QgU3RyaXA8L3RleHQ+PC9zdmc+', name: 'water_test_strip.jpg', size: 245760 }, data: { ph: 7.2, nitrates: 15, chlorine: 2.1 } }, { id: 2, author: 'BirdWatcher92', avatar: '๐Ÿฆœ', timestamp: Date.now() - 4 * 60 * 60 * 1000, // 4 hours ago content: 'BiodiversityEar identified 15 different bird species in my morning recording! Including a rare warbler that hasn\'t been spotted in our area for years. Nature is amazing! ๐ŸŽต', likes: 24, comments: [ { author: 'NatureExpert', content: 'Which warbler species? That\'s incredible!', timestamp: Date.now() - 2 * 60 * 60 * 1000 }, { author: 'BioStudent', content: 'Can you share the recording? Would love to hear it!', timestamp: Date.now() - 1 * 60 * 60 * 1000 } ], type: 'biodiversity_scan', location: 'Central City Park', image: { url: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9InNreSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPjxzdG9wIG9mZnNldD0iMCUiIHN0eWxlPSJzdG9wLWNvbG9yOiM4N0NFRUIiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0eWxlPSJzdG9wLWNvbG9yOiM5OERCOEMiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48cmVjdCB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgZmlsbD0idXJsKCNza3kpIi8+PGNpcmNsZSBjeD0iMzIwIiBjeT0iNjAiIHI9IjMwIiBmaWxsPSIjRkZENzAwIi8+PHJlY3QgeD0iMCIgeT0iMjAwIiB3aWR0aD0iNDAwIiBoZWlnaHQ9IjEwMCIgZmlsbD0iIzIyOEIyMiIvPjx0ZXh0IHg9IjIwMCIgeT0iMTUwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTYiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj7wn6acIEJpcmQgV2F0Y2hpbmcgU3BvdDwvdGV4dD48L3N2Zz4=', name: 'bird_watching_spot.jpg', size: 189440 }, data: { speciesCount: 15, rareSpecies: 'Yellow Warbler' } }, { id: 3, author: 'GreenThumb', avatar: '๐ŸŒฟ', timestamp: Date.now() - 24 * 60 * 60 * 1000, // 1 day ago content: 'FloraShield helped me identify an invasive plant species in my garden before it could spread. Early detection is key to protecting our local ecosystem! ๐Ÿ›ก๏ธ', likes: 18, comments: [ { author: 'GardenExpert', content: 'Which species was it? Always good to share for others to watch out for!', timestamp: Date.now() - 20 * 60 * 60 * 1000 } ], type: 'plant_identification', location: 'Home Garden', image: { url: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgZmlsbD0iIzIyOEIyMiIvPjxwYXRoIGQ9Ik0xMDAsMjUwIEwxNTAsMTUwIEwyMDAsMjAwIEwyNTAsMTAwIEwzMDAsMTgwIiBzdHJva2U9IiM5OERCOEMiIHN0cm9rZS13aWR0aD0iOCIgZmlsbD0ibm9uZSIvPjxjaXJjbGUgY3g9IjE1MCIgY3k9IjE1MCIgcj0iMTUiIGZpbGw9IiNGRkQ3MDAiLz48Y2lyY2xlIGN4PSIyNTAiIGN5PSIxMDAiIHI9IjEyIiBmaWxsPSIjRkY2MzQ3Ii8+PHRleHQgeD0iMjAwIiB5PSIyODAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0id2hpdGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiPvCfjL8gSW52YXNpdmUgUGxhbnQgRGV0ZWN0ZWQ8L3RleHQ+PC9zdmc+', name: 'invasive_plant.jpg', size: 156780 }, data: { species: 'Japanese Knotweed', confidence: 92 } }, { id: 4, author: 'CarbonCrusher', avatar: '๐ŸŒณ', timestamp: Date.now() - 6 * 60 * 60 * 1000, // 6 hours ago content: 'Completed my monthly carbon footprint analysis. Managed to reduce my emissions by 23% this month through better transport choices and energy efficiency! ๐Ÿšฒโšก', likes: 31, comments: [ { author: 'EcoCommuter', content: 'Amazing! What transport changes did you make?', timestamp: Date.now() - 3 * 60 * 60 * 1000 } ], type: 'carbon_reduction', data: { reduction: 23, co2Saved: 45 } } ]; setPosts(initialPosts); localStorage.setItem('ecospire_community_posts', JSON.stringify(initialPosts)); }; const handleImageSelect = async (e) => { const file = e.target.files[0]; if (!file) return; try { setIsLoading(true); const processedImage = await imageHandler.processImage(file, { compress: true, maxWidth: 800, quality: 0.8 }); setSelectedImage({ file: file, preview: processedImage.preview, name: processedImage.original.name, size: processedImage.processed.size, processedData: processedImage }); } catch (error) { alert(`Image processing failed: ${error.message}`); console.error('Image processing error:', error); } finally { setIsLoading(false); } }; const removeImage = () => { setSelectedImage(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const getCurrentLocation = () => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; // Simulate reverse geocoding const locations = [ 'Central Park, New York', 'Golden Gate Park, San Francisco', 'Hyde Park, London', 'Vondelpark, Amsterdam', 'Retiro Park, Madrid' ]; const randomLocation = locations[Math.floor(Math.random() * locations.length)]; setSelectedLocation(randomLocation); }, (error) => { console.error('Geolocation error:', error); setSelectedLocation('Location unavailable'); } ); } else { setSelectedLocation('Geolocation not supported'); } }; const handlePostSubmit = async (e) => { e.preventDefault(); if (!newPost.trim()) return; if (!currentUser || currentUser.isGuest) { alert('Please create an account to post in the community!'); onNavigate && onNavigate('Login'); return; } setIsLoading(true); // Process and store image let imageData = null; if (selectedImage) { const imageId = `post_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // Store image using imageHandler const stored = imageHandler.storeImage(selectedImage.processedData, imageId); if (stored) { imageData = { id: imageId, url: selectedImage.preview, name: selectedImage.name, size: selectedImage.size, type: selectedImage.file.type }; } else { // Fallback to direct preview if storage fails imageData = { url: selectedImage.preview, name: selectedImage.name, size: selectedImage.size, type: selectedImage.file.type }; } } const post = { id: Date.now(), author: currentUser.name, avatar: currentUser.avatar, timestamp: Date.now(), content: newPost, likes: 0, comments: [], type: postType, location: selectedLocation || null, image: imageData, data: generatePostData(postType) }; const updatedPosts = [post, ...posts]; setPosts(updatedPosts); localStorage.setItem('ecospire_community_posts', JSON.stringify(updatedPosts)); // Log activity with enhanced points for media posts const points = selectedImage ? 25 : 15; await authManager.logActivity('Posted in community', { type: 'community_post', content: newPost.substring(0, 50) + '...', hasImage: !!selectedImage, postType: postType, points: points }); // Reset form setNewPost(''); setSelectedImage(null); setSelectedLocation(''); setPostType('general'); if (fileInputRef.current) { fileInputRef.current.value = ''; } setIsLoading(false); }; const generatePostData = (type) => { switch (type) { case 'water_test': return { ph: (6.5 + Math.random() * 2).toFixed(1), nitrates: Math.floor(Math.random() * 20), chlorine: (Math.random() * 3).toFixed(1) }; case 'biodiversity_scan': return { speciesCount: Math.floor(Math.random() * 20) + 5, rareSpecies: ['Rare Warbler', 'Endangered Butterfly'][Math.floor(Math.random() * 2)] }; case 'carbon_reduction': return { co2Saved: Math.floor(Math.random() * 50) + 10, reduction: Math.floor(Math.random() * 30) + 10 }; case 'plant_identification': return { species: 'Unknown Plant Species', confidence: Math.floor(Math.random() * 30) + 70 }; default: return {}; } }; const handleLike = async (postId) => { if (!currentUser || currentUser.isGuest) { alert('Please create an account to interact with posts!'); return; } const updatedPosts = posts.map(post => { if (post.id === postId) { return { ...post, likes: post.likes + 1 }; } return post; }); setPosts(updatedPosts); localStorage.setItem('ecospire_community_posts', JSON.stringify(updatedPosts)); // Log activity await authManager.logActivity('Liked community post', { type: 'community_interaction', action: 'like', points: 2 }); }; const handleComment = async (postId, comment) => { if (!currentUser || currentUser.isGuest) { alert('Please create an account to comment!'); return; } if (!comment.trim()) return; const newComment = { author: currentUser.name, content: comment, timestamp: Date.now() }; const updatedPosts = posts.map(post => { if (post.id === postId) { return { ...post, comments: [...post.comments, newComment] }; } return post; }); setPosts(updatedPosts); localStorage.setItem('ecospire_community_posts', JSON.stringify(updatedPosts)); // Log activity await authManager.logActivity('Commented on post', { type: 'community_interaction', action: 'comment', points: 5 }); }; const formatTimeAgo = (timestamp) => { const now = Date.now(); const diff = now - timestamp; const minutes = Math.floor(diff / (1000 * 60)); const hours = Math.floor(diff / (1000 * 60 * 60)); const days = Math.floor(diff / (1000 * 60 * 60 * 24)); if (minutes < 60) return `${minutes} minutes ago`; if (hours < 24) return `${hours} hours ago`; return `${days} days ago`; }; const getPostTypeIcon = (type) => { const icons = { water_test: '๐Ÿ’ง', biodiversity_scan: '๐Ÿฆœ', plant_identification: '๐ŸŒฟ', carbon_reduction: '๐ŸŒณ', general: '๐Ÿ’ฌ' }; return icons[type] || '๐Ÿ’ฌ'; }; return (
{/* Header */}

๐Ÿ‘ฅ GreenPlus by GXS Community

Connect with environmental champions worldwide

{/* User Status */} {currentUser && (
{currentUser.avatar} Welcome, {currentUser.name}! {currentUser.isGuest && ( (Guest Mode - ) )}
)}
{/* Navigation Tabs */}
{[ { id: 'feed', name: 'Community Feed', icon: '๐Ÿ“ฑ' }, { id: 'leaderboard', name: 'Leaderboard', icon: '๐Ÿ†' }, { id: 'stats', name: 'Community Stats', icon: '๐Ÿ“Š' } ].map(tab => ( ))}
{/* Community Feed Tab */} {activeTab === 'feed' && ( <> {/* Create Post */}

Share Your Environmental Impact

{/* Post Type Selector */}