Loading...
Loading...
Loading...
Focus Reef is a React Native Expo mobile application that gamifies focus and productivity through coral reef visualization. Users plant virtual coral during focus sessions, with real-time growth tied to concentration quality. The app features social dive rooms, productivity analytics, AR visualization, and real-world coral restoration impact tracking.
# Focus Reef - Statement of Work (SOW)
## Executive Summary
Focus Reef is a React Native Expo mobile application that gamifies focus and productivity through coral reef visualization. Users plant virtual coral during focus sessions, with real-time growth tied to concentration quality. The app features social dive rooms, productivity analytics, AR visualization, and real-world coral restoration impact tracking.
**Project Duration**: 16 weeks (4 months)
**Platform**: iOS & Android via React Native Expo
**Architecture**: Atomic State + Service Layer with Firebase Backend
**Monetization**: Freemium + Subscriptions + In-App Purchases
---
## Technical Architecture
### Core Architecture Pattern
**Atomic State + Service Layer Architecture**
- **State Management**: Jotai atoms for reactive state
- **Service Layer**: Firebase integration + business logic
- **UI Components**: React Native with NativeWind styling
- **Data Flow**: User Action → Component → Atom → Service → Firebase
### Technology Stack
#### Core Framework
- React Native 0.79 with Expo SDK 53
- TypeScript for type safety
- Expo Router for file-based navigation
#### State & Data Management
- Jotai for atomic state management
- React Native MMKV for local storage
- Firebase Suite (Auth, Firestore, Functions, Storage)
#### UI & Animation
- NativeWind (Tailwind CSS) for styling
- React Native Reanimated 3 for animations
- React Native SVG for coral graphics
- Lottie React Native for complex animations
#### Audio & Media
- Expo AV for ambient soundscapes
- React Native Track Player for background audio
#### Native Features
- Expo Haptics for feedback
- Expo Notifications for alerts
- Expo Background Tasks for timer functionality
- Expo Camera + GL for AR features
#### Monetization & Payments
- Expo In-App Purchases
- RevenueCat for subscription management
### Database Schema
#### Firestore Collections Structure
**Users Collection** (`/users/{userId}`)
```typescript
{
id: string
email: string
displayName: string
avatar?: string
createdAt: timestamp
totalCoins: number
lifetimeMinutes: number
currentStreak: number
subscriptionTier: 'free' | 'lagoon-pass' | 'tide-pro' | 'tide-pro-plus'
defaultTimerDuration: number
preferences: {
sounds: string[]
haptics: boolean
theme: string
notifications: object
}
}
```
**Sessions Collection** (`/users/{userId}/sessions/{sessionId}`)
```typescript
{
id: string
startTime: timestamp
endTime?: timestamp
plannedDuration: number
actualDuration: number
completed: boolean
tag?: string
interruptions: number
coinsEarned: number
coralUnlocked?: string
focusPercentage: number
}
```
**Corals Collection** (`/users/{userId}/corals/{coralId}`)
```typescript
{
id: string
species: string
rarity: 'common' | 'rare' | 'epic' | 'legendary'
unlockedAt: timestamp
size: number
position: { x: number, y: number, z: number }
minutesInvested: number
}
```
**Dive Rooms Collection** (`/diveRooms/{roomId}`)
```typescript
{
id: string
name: string
createdBy: string
maxParticipants: number
plannedDuration: number
status: 'waiting' | 'active' | 'completed'
participants: {
[userId]: {
status: string
coralProgress: number
joinedAt: timestamp
}
}
}
```
---
## Implementation Plan
### Phase 1: Core Foundation (Weeks 1-2)
#### Foundation Setup
- [ ] Create Firebase project with Authentication, Firestore, Functions, Storage
- [ ] Configure Firebase SDK in React Native app
- [ ] Set up environment variables and configuration files
- [ ] Install and configure required dependencies from package.json
- [ ] Set up development and staging environments
#### Authentication System
- [ ] Implement Firebase Auth service wrapper
- [ ] Create login screen with Apple/Google/Email options
- [ ] Build registration flow with email verification
- [ ] Add password reset functionality
- [ ] Implement secure token storage with MMKV
- [ ] Create user profile creation flow
- [ ] Add logout functionality with state cleanup
#### Navigation Structure
- [ ] Configure Expo Router with tab-based navigation
- [ ] Create Timer tab with placeholder screen
- [ ] Create Lagoon tab with placeholder screen
- [ ] Create Analytics tab with placeholder screen
- [ ] Create Social tab with placeholder screen
- [ ] Create Settings tab with basic preferences
- [ ] Implement modal routes for overlays
- [ ] Add navigation guards for authenticated routes
#### Core State Management
- [ ] Create user atom with profile data and preferences
- [ ] Create timer atom with session state management
- [ ] Create app atom for global application state
- [ ] Implement MMKV storage persistence for atoms
- [ ] Add atom persistence for offline functionality
- [ ] Create derived atoms for computed values
- [ ] Add error handling for atom operations
### Phase 2: Timer & Focus System (Weeks 3-4)
#### Timer Core Logic
- [ ] Implement timer service with start/stop/pause functionality
- [ ] Create countdown logic with millisecond precision
- [ ] Add timer state persistence across app lifecycle
- [ ] Implement session completion detection and logging
- [ ] Create timer accuracy validation (±1 second requirement)
- [ ] Add session abandonment handling with data cleanup
- [ ] Implement timer recovery after app crashes
#### Deep Focus Mode
- [ ] Create app state monitoring service using Expo AppState
- [ ] Implement focus tracking with interruption detection
- [ ] Add 10-second grace period before marking interruptions
- [ ] Create focus percentage calculation algorithm
- [ ] Implement bleaching trigger at 3+ interruptions
- [ ] Add focus mode visual indicators and overlays
- [ ] Create educational notifications for focus improvement
#### Background Timer Functionality
- [ ] Configure Expo Background Tasks for timer continuation
- [ ] Implement background timer with notification updates
- [ ] Add timer completion notifications with custom sounds
- [ ] Create foreground service for Android timer continuity
- [ ] Implement timer state sync when app returns to foreground
- [ ] Add low battery detection with timer adjustment options
- [ ] Create background task cleanup on session completion
#### Timer UI Components
- [ ] Design and implement circular timer progress indicator
- [ ] Create "Plant Coral" button with animation
- [ ] Add timer duration selection wheel (5-120 minutes)
- [ ] Implement session tag input with autocomplete
- [ ] Create pause/resume controls with haptic feedback
- [ ] Add session abandonment confirmation modal
- [ ] Implement timer completion celebration screen
### Phase 3: Coral Growth & Visualization (Weeks 5-6)
#### Coral Generation System
- [ ] Create coral species database with rarity tiers
- [ ] Implement coral generation algorithm based on session length
- [ ] Create SVG path definitions for 20+ coral species
- [ ] Add procedural color variation system for coral diversity
- [ ] Implement rarity calculation (common/rare/epic/legendary)
- [ ] Create coral unlock requirements matrix
- [ ] Add seasonal/event-based special coral species
#### Coral Animation Engine
- [ ] Implement React Native Reanimated coral growth animations
- [ ] Create real-time coral progress visualization during sessions
- [ ] Add coral bleaching animation for focus interruptions
- [ ] Implement coral completion celebration with particle effects
- [ ] Create smooth coral placement in 3D reef space
- [ ] Add coral hover and selection interactions
- [ ] Optimize animation performance for 60fps on all devices
#### Reef Visualization
- [ ] Design 3D reef layout system with depth layers
- [ ] Implement coral positioning algorithm to prevent overlaps
- [ ] Create reef background with animated water effects
- [ ] Add reef creatures (fish, sea turtles) as unlockables
- [ ] Implement reef zoom and pan gestures
- [ ] Create reef day/night cycle based on user timezone
- [ ] Add reef health visualization based on recent session quality
#### Coin & Reward System
- [ ] Implement coin earning calculation (1 coin per focused minute)
- [ ] Create coin balance display with animated updates
- [ ] Add bonus coin multipliers for streak achievements
- [ ] Implement daily login bonus coin rewards
- [ ] Create coin spending system for coral unlocks
- [ ] Add coin transaction history and tracking
- [ ] Implement anti-fraud measures for coin earning validation
### Phase 4: Audio & Immersion (Weeks 7-8)
#### Adaptive Soundscape System
- [ ] Source and optimize underwater ambient audio files
- [ ] Implement adaptive audio mixing based on session progress
- [ ] Create whale song audio triggers at session milestones
- [ ] Add crackling reef life sounds with random timing
- [ ] Implement audio fade-in/out during session transitions
- [ ] Create audio preference system with volume controls
- [ ] Optimize audio streaming for battery efficiency <2% drain
#### Background Audio Management
- [ ] Configure React Native Track Player for background audio
- [ ] Implement audio session management for iOS/Android
- [ ] Add audio interruption handling (calls, other apps)
- [ ] Create seamless audio loop system without gaps
- [ ] Implement audio ducking for notifications
- [ ] Add headphone detection with automatic audio switching
- [ ] Create audio quality settings for different network conditions
#### Haptic Feedback System
- [ ] Implement haptic patterns for timer start/stop/pause actions
- [ ] Add subtle haptic pulses for coral growth milestones
- [ ] Create distinctive haptic alerts for session completion
- [ ] Implement haptic warnings for focus interruptions
- [ ] Add haptic intensity settings in user preferences
- [ ] Create haptic feedback for UI interactions and button presses
- [ ] Optimize haptic usage for battery conservation
#### Audio UI Controls
- [ ] Create audio preference screen with sound selection
- [ ] Implement volume sliders for different audio categories
- [ ] Add mute/unmute toggle with visual feedback
- [ ] Create audio preview functionality for sound selection
- [ ] Implement audio crossfade controls for smooth transitions
- [ ] Add accessibility support for audio preferences
- [ ] Create quick audio adjustment controls in timer interface
### Phase 5: Social Features (Weeks 9-10)
#### Dive Room Foundation
- [ ] Create dive room creation modal with name/duration/privacy settings
- [ ] Implement room joining flow with code/link sharing
- [ ] Add room capacity limits (free: 3, premium: 10, max: 20)
- [ ] Create room settings validation and error handling
- [ ] Implement room password protection for private sessions
- [ ] Add room moderation controls for room creators
- [ ] Create room invitation system via deep links
#### Real-time Synchronization
- [ ] Implement Firebase real-time listeners for room updates
- [ ] Create participant status synchronization (joined/active/bleached)
- [ ] Add real-time coral progress sharing between participants
- [ ] Implement group session countdown with synchronized start
- [ ] Create bleaching penalty system affecting all participants
- [ ] Add network reconnection handling with state recovery
- [ ] Implement conflict resolution for simultaneous room updates
#### Social UI Components
- [ ] Design dive room lobby with participant avatars
- [ ] Create real-time participant progress indicators
- [ ] Implement group coral garden visualization
- [ ] Add chat system for pre-session coordination
- [ ] Create participant status badges and indicators
- [ ] Implement room leaderboard with session rankings
- [ ] Add social sharing for completed group sessions
#### Friend System
- [ ] Create friend request sending and receiving system
- [ ] Implement friend list with online status indicators
- [ ] Add friend search by username/email functionality
- [ ] Create friend activity feed with recent sessions
- [ ] Implement friend invitation to dive rooms
- [ ] Add friend removal and blocking functionality
- [ ] Create friend-only dive room privacy option
### Phase 6: Analytics & Insights (Weeks 11-12)
#### Session Analytics Engine
- [ ] Create session data aggregation service
- [ ] Implement productivity metrics calculation (completion rate, average duration)
- [ ] Add streak tracking with daily/weekly/monthly views
- [ ] Create tag-based productivity breakdown analysis
- [ ] Implement time-of-day productivity pattern detection
- [ ] Add focus quality trends with interruption analysis
- [ ] Create comparative analytics (this week vs last week)
#### Interactive Reef Heat Maps
- [ ] Design heat map visualization showing productive vs unproductive areas
- [ ] Implement color-coded coral health based on recent session quality
- [ ] Create interactive heat map with drill-down capabilities
- [ ] Add time-range selection for heat map analysis
- [ ] Implement tag filtering for heat map visualization
- [ ] Create animated transitions between different heat map views
- [ ] Add export functionality for heat map images
#### AI Recommendation System
- [ ] Implement session pattern analysis algorithm
- [ ] Create optimal focus duration prediction based on historical data
- [ ] Add fatigue detection using completion rates and session times
- [ ] Implement personalized break time recommendations
- [ ] Create best time-of-day suggestions for different task types
- [ ] Add weekly focus goal recommendations based on trends
- [ ] Implement recommendation confidence scoring and explanation
#### Analytics UI Dashboard
- [ ] Create overview dashboard with key productivity metrics
- [ ] Implement detailed analytics charts using React Native Chart Kit
- [ ] Add date range selection with calendar integration
- [ ] Create tag-based analytics filtering and comparison
- [ ] Implement analytics data export to CSV format
- [ ] Add analytics sharing functionality with privacy controls
- [ ] Create analytics goal setting and progress tracking
### Phase 7: Monetization & Impact (Weeks 13-14)
#### In-App Purchase System
- [ ] Configure Expo In-App Purchases for iOS and Android
- [ ] Implement Lagoon Pass one-time purchase ($4.99)
- [ ] Create subscription tiers (Tide Pro $1.49/mo, Tide Pro+ $3.99/mo)
- [ ] Add cosmetic coral pack purchases ($0.99-$4.99)
- [ ] Implement purchase validation and receipt verification
- [ ] Create purchase restoration functionality for device transfers
- [ ] Add subscription management and cancellation flows
#### RevenueCat Integration
- [ ] Configure RevenueCat SDK for subscription management
- [ ] Implement subscription status tracking and validation
- [ ] Create subscription upgrade/downgrade flows
- [ ] Add trial period management for new subscribers
- [ ] Implement subscription renewal handling and notifications
- [ ] Create subscription analytics and revenue tracking
- [ ] Add churn prevention with targeted offers
#### Feature Gating System
- [ ] Implement premium feature detection and blocking
- [ ] Create feature upgrade prompts with benefit explanations
- [ ] Add graceful degradation for expired subscriptions
- [ ] Implement feature usage tracking for free tier limits
- [ ] Create unlock animations for premium feature access
- [ ] Add feature preview functionality for free users
- [ ] Implement A/B testing for monetization flows
#### Impact Tracking System
- [ ] Create coral restoration partner API integration
- [ ] Implement donation tracking with receipt generation
- [ ] Add impact badge system for user profiles
- [ ] Create global reef challenge progress tracking
- [ ] Implement leaderboard for top environmental contributors
- [ ] Add impact visualization with real-world coral photos
- [ ] Create ESG reporting functionality for corporate users
### Phase 8: AR & Advanced Features (Weeks 15-16)
#### AR Implementation
- [ ] Configure Expo Camera and GL for AR functionality
- [ ] Implement AR reef projection onto real-world surfaces
- [ ] Create AR session with gesture controls for reef manipulation
- [ ] Add AR coral placement and interaction system
- [ ] Implement AR sharing functionality with screenshots/videos
- [ ] Create AR device capability detection and fallback options
- [ ] Optimize AR performance for smooth 30fps rendering
#### Performance Optimization
- [ ] Implement coral LOD (Level of Detail) for performance scaling
- [ ] Add GPU capability detection with feature adjustment
- [ ] Create memory management for large coral collections
- [ ] Implement background task optimization for battery conservation
- [ ] Add performance monitoring with crash reporting
- [ ] Create smart caching system for coral assets and audio
- [ ] Implement progressive loading for large reef visualizations
#### Accessibility & Polish
- [ ] Add VoiceOver/TalkBack support for all interactive elements
- [ ] Implement high contrast mode for accessibility
- [ ] Create voice navigation options for timer controls
- [ ] Add screen reader support for analytics data
- [ ] Implement gesture alternatives for motor accessibility
- [ ] Create text scaling support for visual accessibility
- [ ] Add color blind friendly coral color schemes
#### Beta Testing Preparation
- [ ] Implement feature flags for gradual feature rollouts
- [ ] Create beta testing feedback collection system
- [ ] Add crash reporting with Firebase Crashlytics
- [ ] Implement analytics tracking for user behavior analysis
- [ ] Create app store optimization assets (screenshots, descriptions)
- [ ] Add privacy policy and terms of service integration
- [ ] Implement GDPR compliance with data export/deletion
---
## Risk Management
### High Priority Risks
**Battery Optimization**
- Risk: Background timer drains battery >2% per hour
- Mitigation: Profile early, optimize background tasks, implement smart polling
- Monitoring: Battery usage analytics, user feedback
**Real-time Synchronization**
- Risk: Dive room participants lose sync during network issues
- Mitigation: Local state with periodic sync, conflict resolution, fallback polling
- Monitoring: Connection quality metrics, sync failure rates
**SVG Animation Performance**
- Risk: Complex coral animations cause frame drops on older devices
- Mitigation: LOD system, performance profiling, animation limiting
- Monitoring: Frame rate analytics, device performance metrics
### Medium Priority Risks
**Deep Focus Implementation**
- Risk: App monitoring unreliable across iOS/Android versions
- Mitigation: Graceful degradation, user education, notification reminders
- Monitoring: Focus accuracy rates, false positive tracking
**Offline Functionality**
- Risk: Data loss when users are offline during sessions
- Mitigation: Robust local storage, sync queuing, offline indicators
- Monitoring: Sync success rates, data integrity checks
---
## Success Criteria
### Performance Benchmarks
- Battery usage <2% per hour during active sessions
- Memory usage <100MB peak during normal operation
- 60fps animation frame rate maintained
- <3 second cold start time to timer screen
- <500ms Firebase real-time sync latency
### Quality Metrics
- <0.1% crash rate across all sessions
- >80% test coverage for service layer
- <50MB total app bundle size
- 100% timer functionality available offline
- ±1 second timer accuracy over 25-minute sessions
### User Experience Goals
- <5% false positive rate for interruption detection
- Coral unlock animations complete within 3 seconds
- All dive room participants see updates within 1 second
- Zero session data loss during app crashes
- Sub-1 second response time for all user interactions
---
## Project Deliverables
### Code Deliverables
- Complete React Native Expo application with all features
- Firebase backend configuration and cloud functions
- Comprehensive test suite with >80% coverage
- CI/CD pipeline for automated builds and deployments
- App store ready builds for iOS and Android
### Documentation
- Technical documentation for all APIs and services
- User manual and onboarding guide
- Privacy policy and terms of service
- App store listings and marketing materials
- Developer handoff documentation
### Analytics & Monitoring
- Firebase Analytics implementation
- Crashlytics error tracking
- Performance monitoring dashboard
- User behavior analytics setup
- A/B testing framework configuration
---
## Next Steps
This SOW provides a comprehensive roadmap for developing Focus Reef. Implementation should begin with Phase 1 foundation work, ensuring each phase is completed and tested before proceeding to the next.
**IMPORTANT**: This SOW.md file should be updated throughout development to track progress. As implementation tasks are completed, check them off using GitHub's checkbox syntax. Update any changed requirements or technical decisions in their respective sections to maintain an accurate project record.
---
*Last Updated: [Current Date]*
*Status: Ready for Implementation*
*Confidence Level: 95%*
**GitHub**:<https://github.com/HammerLynch/MSDS6306_Case_Study_2>
*Company Name : SK C&C*
Reference for building PL/SQL or Scala ETL pipelines. Types use PostgreSQL names as emitted by Diesel.
This document describes how to use the analytics system in the application.