import React, { useState, useEffect, lazy, Suspense } from 'react'
import { motion, AnimatePresence, MotionConfig, LazyMotion, domAnimation } from 'framer-motion'
import {
Backpack,
Heart,
MapPin,
Phone,
Shirt,
Users,
Building2,
BookOpenText,
Quote,
FileText,
X,
DollarSign,
Award,
Settings,
UserCheck,
School,
ClipboardList,
Calendar,
FileCheck,
AlertCircle,
Package,
Truck,
Plus,
Lock,
Database,
Check,
Clock,
Bell,
BellRing,
BarChart3,
TrendingUp,
Languages,
Brain,
Cpu,
Download,
WifiOff,
ChevronDown,
Eye,
Zap,
Target,
Activity,
} from 'lucide-react'
// Phase 3: AI Components (lazy — portal routes only)
const AIAssistancePortal = lazy(() => import('./components/AIAssistancePortal'))
// Phase 3B: Enterprise Components (lazy — portal routes only)
const AdvancedAnalyticsDashboard = lazy(() => import('./components/AdvancedAnalyticsDashboard'))
const MobileVolunteerApp = lazy(() => import('./components/MobileVolunteerApp'))
const StaffTrainingDashboard = lazy(() => import('./components/StaffTrainingDashboard'))
const MimChatAgent = lazy(() => import('./components/MimChatAgent'))
import { AppPageShell as PageShell } from './components/layout/AppPageShell'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import { LanguageProvider, useLanguage } from './contexts/LanguageContext'
import { NotificationProvider, useNotifications } from './contexts/NotificationContext'
// Lazy route chunks — home, donate, assistance (motion-heavy / form pages)
const HomePage = lazy(() => import('./routes/HomePageRoute'))
const DonatePage = lazy(() => import('./routes/DonatePageRoute'))
const AssistanceRequestPage = lazy(() => import('./routes/AssistanceRequestPageRoute'))
// Phase 4: Extracted Components
import { Navigation } from './components/Navigation'
import { SiteHeader } from './components/SiteHeader'
import { Footer } from './components/Footer'
import { BrandAssetsPage } from './pages/BrandPage'
import {
AboutPage,
ContactPage,
EventsPage,
MissionPage,
StoriesIntroBlock,
WhatWeDoPage,
} from './pages/foundation'
import { EMAILS, SITE, mailto } from './content/siteContent'
import { FormSuccess } from './components/ui/FormSuccess'
import { submitContactFromForm } from './lib/submitContactFromForm'
import { MimApiError } from './lib/mimApi'
function RouteFallback({ label = 'Loading…' }: { label?: string }) {
return (
{label}
)
}
function PortalRouteFallback() {
return (
Loading portal…
)
}
function LazyPortal({ children }: { children: React.ReactNode }) {
return }>{children}
}
function LazyRoute({ children, label }: { children: React.ReactNode; label?: string }) {
return }>{children}
}
/**
* Miracles in Motion — Complete Non-Profit Website
* A comprehensive 501(c)3 organization website with modern design,
* donation processing, volunteer management, and impact tracking.
*/
/* ===================== Phase 2: Enhanced Context Systems ===================== */
/* ===================== Analytics Tracking ===================== */
function trackEvent(eventName: string, properties: Record = {}) {
// In production, integrate with Google Analytics, Mixpanel, or similar
if (typeof window !== 'undefined' && (window as any).gtag) {
(window as any).gtag('event', eventName, properties)
}
console.log(`Analytics: ${eventName}`, properties)
}
function useAnalytics() {
const [analyticsData, setAnalyticsData] = useState(() => ({
pageViews: [
{ page: 'Home', views: 2847, trend: 12.5 },
{ page: 'Donate', views: 1203, trend: 8.3 },
{ page: 'Volunteer', views: 856, trend: -2.1 },
{ page: 'Stories', views: 645, trend: 15.8 },
{ page: 'About', views: 432, trend: 5.2 }
],
donationMetrics: { amount: 45280, count: 186, recurring: 67 },
userEngagement: { sessions: 3241, avgDuration: 185, bounceRate: 0.34 },
conversionRates: { donation: 0.078, volunteer: 0.032, contact: 0.156 }
}))
const refreshAnalytics = () => {
// Simulate real-time data updates
setAnalyticsData(prev => ({
...prev,
pageViews: prev.pageViews.map(pv => ({
...pv,
views: pv.views + Math.floor(Math.random() * 10),
trend: (Math.random() - 0.5) * 20
})),
donationMetrics: {
...prev.donationMetrics,
amount: prev.donationMetrics.amount + Math.floor(Math.random() * 500),
count: prev.donationMetrics.count + Math.floor(Math.random() * 3)
}
}))
}
useEffect(() => {
const interval = setInterval(refreshAnalytics, 30000) // Update every 30 seconds
return () => clearInterval(interval)
}, [])
return { analyticsData, refreshAnalytics }
}
/* ===================== PWA Features ===================== */
function usePWA() {
const [isOnline, setIsOnline] = useState(navigator.onLine)
const [installPrompt, setInstallPrompt] = useState(null)
const [isInstallable, setIsInstallable] = useState(false)
useEffect(() => {
const handleOnline = () => setIsOnline(true)
const handleOffline = () => setIsOnline(false)
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
// PWA Install Prompt
const handleBeforeInstallPrompt = (e: any) => {
e.preventDefault()
setInstallPrompt(e)
setIsInstallable(true)
}
window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
return () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
}
}, [])
const installApp = async () => {
if (!installPrompt) return false
installPrompt.prompt()
const { outcome } = await installPrompt.userChoice
if (outcome === 'accepted') {
trackEvent('pwa_installed')
setInstallPrompt(null)
setIsInstallable(false)
return true
}
return false
}
return { isOnline, isInstallable, installApp }
}
/* ===================== SEO Meta Tags Component ===================== */
function SEOHead({ title, description, image }: { title?: string, description?: string, image?: string }) {
useEffect(() => {
// Update document title
if (title) {
document.title = `${title} | Miracles in Motion`
}
// Update meta description
const metaDescription = document.querySelector('meta[name="description"]')
if (description && metaDescription) {
metaDescription.setAttribute('content', description)
}
// Update Open Graph tags
const updateOGTag = (property: string, content: string) => {
let tag = document.querySelector(`meta[property="${property}"]`)
if (!tag) {
tag = document.createElement('meta')
tag.setAttribute('property', property)
document.head.appendChild(tag)
}
tag.setAttribute('content', content)
}
updateOGTag('og:title', title || `${SITE.name} — ${SITE.brandMessage}`)
updateOGTag('og:description', description || 'Faith-centered nonprofit bringing hope, outreach, emergency assistance, and wellness support to families in Los Angeles County.')
updateOGTag('og:image', image || `${SITE.url}/og-image.png`)
updateOGTag('og:type', 'website')
}, [title, description, image])
return null
}
/* ===================== Types ===================== */
interface IconProps {
className?: string
}
interface AnalyticsData {
pageViews: { page: string; views: number; trend: number }[]
donationMetrics: { amount: number; count: number; recurring: number }
userEngagement: { sessions: number; avgDuration: number; bounceRate: number }
conversionRates: { donation: number; volunteer: number; contact: number }
}
interface CardProps {
title: string
icon: React.ComponentType
children: React.ReactNode
}
interface PolicySectionProps {
id: string
title: string
children: React.ReactNode
}
/* ===================== Shared UI ===================== */
export function useHashRoute() {
const parse = () => (window.location.hash?.slice(1) || "/")
const [route, setRoute] = useState(parse())
useEffect(() => {
const onHash = () => setRoute(parse())
window.addEventListener("hashchange", onHash)
return () => window.removeEventListener("hashchange", onHash)
}, [])
return route
}
/* ===================== Legacy Router Component (Repurposed) ===================== */
/* ===================== Shared UI ===================== */
function SkipToContent() {
return (
Skip to content
)
}
// Nav component has been extracted to ./components/Navigation.tsx
// LogoMark component has been extracted to ./components/ui/LogoMark.tsx
/* ===================== Home Page ===================== */
/* ===================== Pages ===================== */
function VolunteerPage() {
const [submitted, setSubmitted] = useState(null)
const [submitting, setSubmitting] = useState(false)
const [formError, setFormError] = useState(null)
const onVolunteerSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
setFormError(null)
try {
const res = await submitContactFromForm(e.currentTarget, 'volunteer')
setSubmitted(res.message)
e.currentTarget.reset()
} catch (err) {
setFormError(err instanceof MimApiError ? err.message : 'Could not submit. Please email info@mim4u.org.')
} finally {
setSubmitting(false)
}
}
return (
Sign-up form
{submitted ? (
setSubmitted(null)} />
) : (
)}
)
}
function SponsorsPage() {
const [submitted, setSubmitted] = useState(null)
const [submitting, setSubmitting] = useState(false)
const [formError, setFormError] = useState(null)
const onSponsorSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
setFormError(null)
try {
const res = await submitContactFromForm(e.currentTarget, 'sponsor')
setSubmitted(res.message)
e.currentTarget.reset()
} catch (err) {
setFormError(err instanceof MimApiError ? err.message : 'Could not submit. Please email info@mim4u.org.')
} finally {
setSubmitting(false)
}
}
const tiers = [
{ name: "Bronze", amt: "$2,500", perks: ["Logo on website", "Social thank-you", "Quarterly impact note"] },
{ name: "Silver", amt: "$5,000", perks: ["All Bronze", "Logo on event signage", "Volunteer day for your team"] },
{ name: "Gold", amt: "$10,000", perks: ["All Silver", "Co-branded kit drive", "Annual report feature"] },
{ name: "Platinum", amt: "$25,000+", perks: ["All Gold", "Program naming opportunity", "Custom partnership plan"] },
]
return (
Brand assets}>
{tiers.map((t) => (
{t.perks.map((p, i) => ({p} ))}
))}
Start a conversation
{submitted ? (
setSubmitted(null)} />
) : (
)}
)
}
function StoriesPage() {
const [submitted, setSubmitted] = useState(null)
const [submitting, setSubmitting] = useState(false)
const [formError, setFormError] = useState(null)
const onStorySubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
setFormError(null)
try {
const res = await submitContactFromForm(e.currentTarget, 'story')
setSubmitted(res.message)
e.currentTarget.reset()
} catch (err) {
setFormError(err instanceof MimApiError ? err.message : 'Could not submit. Please email info@mim4u.org.')
} finally {
setSubmitting(false)
}
}
const stories = [
{ title: "A family found hope again", tag: "Outreach", body: "After a fire displaced their home, a mother and children received emergency support and compassionate guidance through recovery.", by: "Community partner" },
{ title: "Strength after hardship", tag: "Advocacy", body: "A survivor connected with resources and encouragement — reminded that she matters and brighter days are ahead.", by: "Volunteer" },
{ title: "Community showed up", tag: "Events", body: "Neighbors and volunteers came together at an outreach event to serve families with supplies, prayer, and heartfelt support.", by: "Event volunteer" },
]
return (
Read testimonies}>
{stories.map((s, i) => (
{s.tag}
{s.title}
{s.body}
— {s.by}
))}
)
}
function TestimoniesPage() {
const items = [
{ who: "Parent", quote: "They reminded us we were not alone — hope came when we needed it most." },
{ who: "Community partner", quote: "Compassionate, fast, and rooted in faith. Our families felt seen." },
{ who: "Principal", quote: "Attendance improves when kids have what they need." },
]
return (
{items.map((t, i) => (
"{t.quote}"
— {t.who}
))}
)
}
function ImpactReportPage() {
return (
Donate to support more families}>
Miracles in Motion Foundation serves vulnerable individuals and families across Los Angeles County. For impact updates or data requests, contact {SITE.email} .
85%
of donations go directly to programs & outreach
$48 / $72
average grant (supplies / clothing)
How we confirm support
When you submit a request for assistance, we review your situation with care and respond as quickly as possible. All information is handled in line with our Privacy Policy and is never shared for marketing.
)
}
function LegalPage() {
return (
Donate}>
We collect only the data necessary to process donations, volunteer coordination, and email subscriptions. We do not sell or trade personal data. Assistance requests are used only to verify and deliver support; we do not share this data for marketing. You may request access, correction, or deletion at {EMAILS.privacy} .
We never sell, share, or trade donor names or personal information with any other entity, nor send donor mailings on behalf of other organizations. This policy applies to all information received online and offline.
Content is provided "as is" for informational purposes; no warranties.
By submitting content (stories/testimonies), you grant us a non-exclusive license to edit and publish.
Unauthorized scraping or misuse of site content is prohibited.
We use essential cookies for site functionality and, with your consent, privacy-friendly analytics. You can change your choices via the cookie banner or by clearing site data.
Donations are generally non-refundable. If you believe a donation was made in error, contact {EMAILS.donate} within 15 days for assistance.
We accept monetary gifts, in-kind donations for outreach, DAF grants, and publicly traded securities.
In-kind items must be new and appropriate for families in need. We reserve the right to decline gifts not aligned with mission or capacity.
By volunteering, you agree to follow staff instructions; assume ordinary risks associated with volunteering; and release Miracles in Motion from liability for ordinary negligence. You consent to background checks where required and agree to our child-safeguarding rules (no unsupervised time with minors, no personal contact outside events). Under 18 requires guardian consent.
No one-on-one unsupervised interactions with minors.
Report suspected abuse/neglect immediately to authorities and notify staff.
Photography of minors requires prior written consent from a parent/guardian.
We serve individuals and families regardless of race, color, religion, national origin, sex, sexual orientation, gender identity, disability, or any other protected status.
We aim to meet WCAG 2.1 AA standards. If you encounter accessibility barriers, email {EMAILS.access} .
{SITE.name} is a {SITE.legalStatus.toLowerCase()}. EIN {SITE.ein}. Annual reports and Form 990s are available upon request or linked here when published.
State disclosures: Certain states may require additional disclosures for charitable solicitations. Where applicable, our disclosures will be presented on the donation page and receipts.
)
}
/* ===================== Helper Components ===================== */
function PolicySection({ id, title, children }: PolicySectionProps) {
return (
)
}
function Card({ title, icon: Icon, children }: CardProps) {
return (
)
}
// Portals Overview Page
function PortalsPage() {
return (
{/* Admin Portal */}
Administration Portal
Full system access for administrators and directors
Manage all requests & approvals
System configuration & reports
User management & permissions
Access Admin Portal
{/* Volunteer Portal */}
Volunteer Portal
For employees, volunteers, and coordinators
View assigned tasks & deliveries
Schedule & availability management
Access Volunteer Portal
{/* Resource Center Portal */}
Resource Center Portal
For community partners, agencies, and referral organizations
Submit assistance requests
Track request status & approvals
Coordinate delivery & pickup
Access Resource Portal
{/* AI Assistance Portal - Phase 3 */}
AI Assistance Portal
AI-powered request matching and insights
Real-time AI request processing
Smart resource matching & allocation
Predictive analytics & insights
Access AI Portal
{/* Phase 3B: Enterprise Features Section */}
Enterprise Analytics & Management
Advanced tools for organizational optimization and impact tracking
{/* Advanced Analytics */}
Advanced Analytics
Comprehensive impact tracking and predictive insights
Impact forecasting & trend analysis
Resource demand prediction
Geographic performance mapping
View Analytics
{/* Mobile Volunteer App */}
Mobile Volunteer Hub
On-the-go assignment management for field volunteers
GPS-enabled assignment tracking
Real-time status updates
Push notifications & alerts
Launch Mobile App
{/* Staff Training System */}
Staff Training Center
Comprehensive AI platform training and adoption
Certification & competency tracking
Onboarding & mentorship programs
Interactive training modules
Access Training
{/* Access Information */}
Access Requirements
New Users
• Contact your supervisor for account setup
• Provide official email address
• Complete background check (if required)
• Attend system orientation session
Login Issues
• Use forgot password link on login page
• Contact IT support: {SITE.email}
• Call main office: (818) 491-6884
• Check email for account activation
)
}
/* ===================== Phase 2: UI Components ===================== */
// Real-time Notification System
export function NotificationCenter() {
const { notifications, markAsRead, clearAll, unreadCount } = useNotifications()
const [isOpen, setIsOpen] = useState(false)
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Element
if (isOpen && !target.closest('[data-notification-center]')) {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen])
return (
setIsOpen(!isOpen)}
className="relative p-2 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-lg transition-colors"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
{unreadCount > 0 ? : }
{unreadCount > 0 && (
{unreadCount > 9 ? '9+' : unreadCount}
)}
{isOpen && (
Notifications
{notifications.length > 0 && (
Clear All
)}
{notifications.length === 0 ? (
) : (
notifications.map((notification) => (
markAsRead(notification.id)}
whileHover={{ x: 4 }}
>
{notification.type === 'success' ?
:
notification.type === 'error' ?
:
notification.type === 'warning' ?
:
}
{notification.title}
{notification.message}
{new Date(notification.timestamp).toLocaleString()}
{!notification.read && (
)}
))
)}
)}
)
}
// Language Selector Component
export function LanguageSelector() {
const { currentLanguage, languages, changeLanguage } = useLanguage()
const [isOpen, setIsOpen] = useState(false)
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Element
if (isOpen && !target.closest('[data-language-selector]')) {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen])
return (
setIsOpen(!isOpen)}
className="flex items-center gap-2 p-2 text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-lg transition-colors"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
{currentLanguage.flag}
{isOpen && (
{languages.map((language) => (
{
changeLanguage(language.code)
setIsOpen(false)
}}
className={`w-full flex items-center gap-3 p-3 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors first:rounded-t-xl last:rounded-b-xl ${
currentLanguage.code === language.code ? 'bg-primary-50 dark:bg-primary-900/20' : ''
}`}
whileHover={{ x: 4 }}
>
{language.flag}
{language.name}
{language.nativeName}
{currentLanguage.code === language.code && (
)}
))}
)}
)
}
// PWA Install Prompt
function PWAInstallPrompt() {
const { isInstallable, installApp } = usePWA()
const [showPrompt, setShowPrompt] = useState(false)
useEffect(() => {
if (isInstallable) {
const timer = setTimeout(() => setShowPrompt(true), 3000)
return () => clearTimeout(timer)
}
}, [isInstallable])
if (!showPrompt) return null
return (
Install Miracles in Motion
Get faster access and offline features by installing our app
setShowPrompt(false)}
className="text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300"
aria-label="Dismiss install prompt"
>
{
const success = await installApp()
if (success) setShowPrompt(false)
}}
className="btn-primary text-sm px-4 py-2 flex-1"
>
Install
setShowPrompt(false)}
className="btn-secondary text-sm px-4 py-2"
>
Later
)
}
/* ===================== Authentication Components ===================== */
function LoginForm({ requiredRole }: { requiredRole?: 'admin' | 'volunteer' | 'resource' }) {
const { login, isLoading } = useAuth()
const [formData, setFormData] = useState({ email: '', password: '' })
const [error, setError] = useState('')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
const success = await login(formData.email, formData.password)
if (!success) {
setError('Invalid credentials. Please try again.')
}
}
const getRoleHint = () => {
switch (requiredRole) {
case 'admin': return 'Use an email containing "admin" to access admin features'
case 'volunteer': return 'Use an email containing "volunteer" for volunteer access'
case 'resource': return 'Use any other email for resource center access'
default: return 'Enter your credentials to access the portal'
}
}
return (
{requiredRole ? `${requiredRole.charAt(0).toUpperCase() + requiredRole.slice(1)} Portal` : 'Portal Access'}
Sign in to access your dashboard
)
}
function PortalWrapper({ children, requiredRole }: { children: React.ReactNode, requiredRole?: 'admin' | 'volunteer' | 'resource' }) {
const { user } = useAuth()
if (!user) {
return
}
if (requiredRole && user.role !== requiredRole) {
return (
Access Denied
You don't have permission to access the {requiredRole} portal.
)
}
return <>{children}>
}
// Admin Portal Dashboard
function AdminPortalPage() {
const { user, logout } = useAuth()
const [stats] = useState({
pendingRequests: 23,
activeVolunteers: 47,
deliveriesToday: 8,
monthlyBudget: 15000,
monthlySpent: 8250
})
useEffect(() => {
trackEvent('admin_portal_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
Sign Out
}
>
{/* Quick Stats */}
Pending Requests
{stats.pendingRequests}
Active Volunteers
{stats.activeVolunteers}
Deliveries Today
{stats.deliveriesToday}
Budget Used
{Math.round((stats.monthlySpent / stats.monthlyBudget) * 100)}%
{/* Recent Requests */}
Recent Assistance Requests
View All
{[
{ student: 'Maria S.', school: 'San Fernando Valley', need: 'Emergency essentials', priority: 'High', time: '2 hours ago' },
{ student: 'James R.', school: 'South LA', need: 'Clothing & outreach', priority: 'Medium', time: '4 hours ago' },
{ student: 'Ana L.', school: 'East LA', need: 'Resource navigation', priority: 'Low', time: '1 day ago' }
].map((request, i) => (
{request.student}
{request.priority}
{request.school}
{request.need}
))}
{/* Quick Actions */}
Quick Actions
Create New User
Approve Pending Requests
Generate Reports
System Settings
)
}
// Volunteer Portal Dashboard
function VolunteerPortalPage() {
const { user, logout } = useAuth()
useEffect(() => {
trackEvent('volunteer_portal_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
Sign Out
}
>
{/* Today's Tasks */}
Today's Schedule
Tuesday, March 14, 2024
{[
{ time: '9:00 AM', task: 'Outreach kit assembly', location: 'Main warehouse', students: 12 },
{ time: '1:00 PM', task: 'Delivery route — Valley area', location: 'LA County', students: 5 },
{ time: '3:30 PM', task: 'Inventory — seasonal clothing', location: 'Storage room B', students: null }
].map((task, i) => (
{task.task}
{task.location}
{task.students &&
{task.students} families served
}
Complete
))}
{/* Assigned Deliveries */}
Pending Deliveries
{[
{ student: 'Sofia M.', items: 'Essentials kit', school: 'San Fernando Valley', deadline: 'Tomorrow' },
{ student: 'Carlos R.', items: 'Winter clothing', school: 'South LA', deadline: 'Friday' },
{ student: 'Emma K.', items: 'Wellness navigation', school: 'East LA', deadline: 'Next week' }
].map((delivery, i) => (
{delivery.student}
{delivery.deadline}
{delivery.items}
{delivery.school}
))}
{/* Volunteer Stats */}
)
}
// Resource Center Portal Dashboard
function ResourcePortalPage() {
const { user, logout } = useAuth()
useEffect(() => {
trackEvent('resource_portal_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
Sign Out
}
>
{/* Quick Submit */}
Quick Request Submission
Submit a new assistance request
{/* Request Status */}
Your Recent Requests
View All Requests
{[
{ id: 'REQ-2024-0342', student: 'Maria Santos', status: 'In Progress', need: 'Emergency essentials', submitted: '2 days ago', eta: 'Tomorrow' },
{ id: 'REQ-2024-0341', student: 'James Rodriguez', status: 'Approved', need: 'Clothing & outreach', submitted: '3 days ago', eta: 'Today' },
{ id: 'REQ-2024-0340', student: 'Ana Lopez', status: 'Delivered', need: 'Resource navigation', submitted: '1 week ago', eta: 'Completed' }
].map((request, i) => (
{request.id}
{request.status}
{request.submitted}
{request.student}
{request.need}
ETA: {request.eta}
View Details
))}
{/* Stats & Resources */}
Monthly Summary
Requests Submitted
12
Students Helped
28
Avg. Response Time
18 hrs
)
}
// Advanced Analytics Dashboard
function AnalyticsDashboard() {
const { user, logout } = useAuth()
const { analyticsData, refreshAnalytics } = useAnalytics()
const { addNotification } = useNotifications()
useEffect(() => {
trackEvent('analytics_dashboard_view', { user_id: user?.id, user_role: user?.role })
}, [])
const handleRefresh = () => {
refreshAnalytics()
addNotification({
type: 'success',
title: 'Data Refreshed',
message: 'Analytics data has been updated with the latest information'
})
}
return (
Refresh
Sign Out
}
>
{/* Key Metrics */}
Total Donations
${analyticsData.donationMetrics.amount.toLocaleString()}
+12.5%
vs last month
+8.3%
vs last month
+15.2%
vs last month
Conversion Rate
{(analyticsData.conversionRates.donation * 100).toFixed(1)}%
+3.1%
vs last month
{/* Page Views Chart */}
Page Performance
Last 30 days
{analyticsData.pageViews.map((page, index) => (
0 ? 'bg-green-500' : page.trend < 0 ? 'bg-red-500' : 'bg-gray-400'
}`} />
{page.page}
{page.views.toLocaleString()} views
0 ? 'text-green-600' : page.trend < 0 ? 'text-red-600' : 'text-gray-600'
}`}>
{page.trend > 0 ? '+' : ''}{page.trend.toFixed(1)}%
))}
{/* Real-time Activity */}
Recent Activity
{[
{ action: 'New donation', details: '$125 from Sarah M.', time: '2 minutes ago', icon: Heart },
{ action: 'Volunteer signup', details: 'John D. registered', time: '8 minutes ago', icon: Users },
{ action: 'Assistance request', details: 'San Fernando Valley', time: '15 minutes ago', icon: MapPin },
{ action: 'Story shared', details: 'Maria\'s success story', time: '1 hour ago', icon: BookOpenText }
].map((activity, index) => (
{activity.action}
{activity.details}
{activity.time}
))}
Impact Summary
Backpacks Distributed
342
)
}
// Phase 3: AI Portal Page
function AIPortalPage() {
const { user, logout } = useAuth()
useEffect(() => {
trackEvent('ai_portal_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
Model Status
Sign Out
}
>
)
}
// Phase 3B: Enterprise Feature Pages
function AdvancedAnalyticsPage() {
const { user, logout } = useAuth()
useEffect(() => {
trackEvent('advanced_analytics_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
)
}
function MobileVolunteerPage() {
const { user } = useAuth()
useEffect(() => {
trackEvent('mobile_volunteer_view', { user_id: user?.id })
}, [])
return (
)
}
function StaffTrainingPage() {
const { user, logout } = useAuth()
useEffect(() => {
trackEvent('staff_training_view', { user_id: user?.id, user_role: user?.role })
}, [])
return (
)
}
function NotFoundPage() {
return (
404
Page not found
The page you're looking for doesn't exist.
Go home
)
}
function BackgroundDecor() {
return (
)
}
// Footer component has been extracted to ./components/Footer.tsx
function StickyDonate() {
return (
)
}
const COOKIE_CONSENT_KEY = 'mim_cookie_consent'
function CookieBanner() {
const [show, setShow] = useState(() => {
if (typeof window === 'undefined') return true
return window.localStorage.getItem(COOKIE_CONSENT_KEY) === null
})
const persistAndClose = (choice: 'accept' | 'decline') => {
try {
window.localStorage.setItem(COOKIE_CONSENT_KEY, choice)
} catch (_) { /* ignore */ }
setShow(false)
}
if (!show) return null
return (
We use cookies to improve your experience. By continuing, you agree to our{' '}
cookie policy .
persistAndClose('accept')}
className="btn-primary text-xs px-4 py-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
aria-label="Accept cookies"
>
Accept
persistAndClose('decline')}
className="btn-secondary text-xs px-4 py-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
aria-label="Decline non-essential cookies"
>
Decline
)
}
/* ===================== Main App Component ===================== */
export default function App() {
return (
)
}
function AppContent() {
const [currentPath, setCurrentPath] = useState(window.location.hash.slice(1) || '/')
const [darkMode, setDarkMode] = useState(() => {
if (typeof window !== 'undefined') {
return localStorage.getItem('darkMode') === 'true' ||
(!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)
}
return false
})
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
const { isOnline } = usePWA()
const { addNotification } = useNotifications()
useEffect(() => {
document.getElementById('mim-static-hero')?.classList.add('is-hidden')
}, [])
useEffect(() => {
const handleHashChange = () => setCurrentPath(window.location.hash.slice(1) || '/')
window.addEventListener('hashchange', handleHashChange)
return () => window.removeEventListener('hashchange', handleHashChange)
}, [])
useEffect(() => {
document.documentElement.classList.toggle('dark', darkMode)
localStorage.setItem('darkMode', darkMode.toString())
}, [darkMode])
// Online/Offline notifications
useEffect(() => {
const handleOnline = () => {
addNotification({
type: 'success',
title: 'Back Online',
message: 'Your internet connection has been restored'
})
}
const handleOffline = () => {
addNotification({
type: 'warning',
title: 'Connection Lost',
message: "You're currently offline. Some features may be limited."
})
}
if (!isOnline) {
handleOffline()
}
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
return () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
}
}, [isOnline, addNotification])
useEffect(() => {
document.title =
currentPath === '/'
? `${SITE.name} — ${SITE.brandMessage}`
: `Miracles in Motion — ${currentPath.replace('/', '').replace(/-/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase())}`
}, [currentPath])
const renderPage = () => {
switch (currentPath) {
case '/':
return
case '/donate':
return
case '/volunteers':
return
case '/sponsors':
return
case '/stories':
return
case '/testimonies':
return
case '/legal':
return
case '/brand':
return
case '/about':
return
case '/mission':
return
case '/what-we-do':
return
case '/events':
return
case '/contact':
return
case '/impact':
return
case '/request-assistance':
return
case '/portals':
return
case '/admin-portal':
return
case '/volunteer-portal':
return
case '/resource-portal':
return
case '/analytics':
return
case '/ai-portal':
return
case '/advanced-analytics':
return
case '/mobile-volunteer':
return
case '/staff-training':
return
default:
return
}
}
return (
{/* Offline Indicator */}
{!isOnline && (
You're currently offline
)}
{renderPage()}
{![
'/admin-portal',
'/volunteer-portal',
'/resource-portal',
'/analytics',
'/ai-portal',
'/advanced-analytics',
'/mobile-volunteer',
'/staff-training'
].includes(currentPath) && (
)}
)
}