Install MatchPlay Pro AI

Get quick access to your dashboard. Install our app for a better experience!

FlutterFlow Migration

Complete FlutterFlow Rebuild Prompt

Comprehensive specification for recreating MatchPlay Pro AI in FlutterFlow

Prompt Preview
# BUILD MATCHPLAY PRO AI IN FLUTTERFLOW - COMPLETE SPECIFICATION

## PROJECT OVERVIEW

Create a comprehensive sports analytics and performance tracking platform called "MatchPlay Pro AI" supporting 5 racket sports: Table Tennis, Tennis, Badminton, Squash, and Pickleball. This is a mobile-first application (iOS & Android) with web support, designed to help competitive players track matches, analyze opponents, improve performance, and connect with coaches.

---

## CORE FEATURES TO BUILD

### 1. AUTHENTICATION & USER MANAGEMENT
- Email/password authentication with Firebase Auth
- User profile with fields:
  - full_name, email, profile_image_url, bio, location, country, phone
  - preferred_sport (dropdown: tabletennis, tennis, badminton, squash, pickleball)
  - clubs (array), teams (array), leagues (array)
  - show_profile_publicly, show_match_stats_publicly (booleans)
  - onboarding_completed (boolean)
  - role (enum: "user", "admin")
- Onboarding flow for new users to select account type (Player/Coach) and preferred sport
- Profile edit page with image upload (Firebase Storage)
- Public player profiles viewable by other users

### 2. MULTI-SPORT ARCHITECTURE
Create a sport configuration system that dynamically adapts the UI and terminology:

**Sport Configurations:**
- Table Tennis: Terms (serve, bat, rubber), Colors (green gradients), Scoring (11 points/game, 5 games/match)
- Tennis: Terms (serve, racquet, strings), Colors (orange gradients), Scoring (Games, Sets, Match)
- Badminton: Terms (serve, racquet, shuttlecock), Colors (blue gradients), Scoring (21 points/game, 3 games/match)
- Squash: Terms (serve, racquet, ball), Colors (red gradients), Scoring (11 points/game, 5 games/match)
- Pickleball: Terms (serve, paddle, ball), Colors (yellow gradients), Scoring (11 points/game, 3 games/match)

**Implementation:**
- Store current sport selection in app state (provider/state management)
- All screens dynamically use sport-specific terminology and colors
- Sport selector dropdown in navigation menu
- Filter all data queries by current sport

### 3. MATCH TRACKING SYSTEM

**Match Entity Schema:**
```
Match {
  id: string
  user_id: string (creator)
  opponent_id: string (FK)
  opponent_partner_id: string (optional, for doubles)
  player_partner_id: string (optional, for doubles)
  sport: enum (tabletennis, tennis, badminton, squash, pickleball)
  match_format: enum (singles, doubles)
  match_date: date
  location: string
  match_type: enum (friendly, league, tournament, practice, custom)
  league_name: string
  tournament_name: string
  
  sets: array of {
    player_score: int
    opponent_score: int
    games: string (e.g., "6-4")
  }
  
  final_result: enum (win, loss)
  duration_minutes: int
  player_serves_first: boolean
  video_urls: array of strings
  notes: string
  show_on_profile: boolean
  created_date: timestamp
}
```

**Match Recording Flow:**
1. "Record Match" button → Match form page
2. Select/create opponent (autocomplete search)
3. Choose match format (singles/doubles)
4. Select match type, date, location
5. Enter set-by-set scores with dynamic score entry widgets
6. Optional: Add match notes, upload video files
7. Save creates Match record
8. View match in "Matches" list with filters (sport, result, opponent, date range)

**Match Detail View:**
- Score card with set-by-set breakdown
- Opponent profile quick view
- Match statistics (duration, serve first, etc.)
- Video gallery if videos attached
- Edit/Delete options
- Share match card feature:
  - Generate shareable match card image with score, opponent, date, and optional "Banter Box" message
  - Export as PNG/JPG for social media
  - Quick share buttons for Facebook, Twitter, Instagram, WhatsApp
  - Copy link to share match details
  - Optional privacy setting per match (public/private sharing)

### 4. OPPONENT INTELLIGENCE SYSTEM

**Opponent Entity Schema:**
```
Opponent {
  id: string
  user_id: string (creator)
  name: string
  sport: enum
  playing_style: enum (sport-specific options)
  dominant_hand: enum (right, left)
  club: string
  
  // Table Tennis specific
  bat_rubbers_setup: enum (normal_both_sides, combination_long_pips, etc.)
  
  strengths: array of strings
  weaknesses: array of strings
  notes: string
  avatar_color: string (hex)
  created_date: timestamp
}
```

**Opponent Profile Features:**
1. List view with avatar circles (colored by avatar_color), name, club
2. Search and filter by name, club, playing style
3. Opponent detail page showing:
   - Profile info (name, club, style, hand, equipment)
   - Strengths tags (chips)
   - Weaknesses tags (chips)
   - Match history vs this opponent (list of Match records)
   - Win/loss statistics
   - Effective tactics used against them
   - Notes section
4. Add/Edit opponent forms with tag input for strengths/weaknesses
5. Share opponent profile with other players (via share dialog)

### 5. FIXTURES & TEAM MANAGEMENT

**Team Entity Schema:**
```
Team {
  id: string
  user_id: string (creator)
  team_name: string
  league_name: string
  league_url: string
  sport: enum
  color: string (hex)
  last_sync_date: timestamp
}
```

**Fixture Entity Schema:**
```
Fixture {
  id: string
  user_id: string (creator)
  team_id: string (FK)
  opponent_name: string
  sport: enum
  fixture_date: date
  fixture_time: string
  venue: string
  competition_type: enum (league, cup, friendly, tournament)
  league_name: string
  team_name: string
  home_away: enum (home, away)
  notes: string
  result: string (filled after match)
  status: enum (scheduled, completed, cancelled, postponed)
  reminder_sent: boolean
}
```

**Features:**
1. My Teams page: List of user's teams with color-coded cards
2. Add team form: team name, league, sport, color picker
3. Add fixture manually: opponent, date, time, venue, type
4. Calendar view of fixtures (month view with color dots by team)
5. Upcoming fixtures list widget on dashboard
6. Convert completed fixture to Match record

### 6. DASHBOARD & ANALYTICS

**Dashboard Widgets:**
1. Welcome banner with user name and sport
2. Quick stats cards:
   - Total matches
   - Win rate percentage
   - Recent form (last 10 matches W/L)
   - Matches this month
3. Recent matches list (last 5) with opponent, date, result
4. Performance chart (last 12 months, wins vs losses by month)
5. Upcoming fixtures widget
6. Featured coaches carousel
7. Goals widget (create/track improvement goals)
8. Achievement badges earned

**Performance Analytics Page:**
- Win rate by opponent
- Win rate by match type (league, tournament, friendly)
- Win rate over time (line chart)
- Most common final scores
- Average match duration
- Serve first win rate

### 7. COACHING PLATFORM

**Coach Entity Schema:**
```
Coach {
  id: string
  user_id: string (FK to User)
  full_name: string
  sport: enum
  specialty: string
  bio: string (long text)
  experience_years: int
  certifications: array of strings
  playing_level: enum (recreational, club, regional, national, international)
  coaching_style: array of strings
  hourly_rate: decimal
  rate_currency: enum (GBP, USD, EUR, AUD, CAD)
  location: string
  availability_online: boolean
  availability_in_person: boolean
  contact_email: string
  phone: string
  hide_email: boolean
  hide_phone: boolean
  profile_image_url: string
  video_intro_url: string
  rating: decimal (0-5)
  total_sessions: int
  total_reviews: int
  languages: array of strings
  approved: boolean
  hidden: boolean
  featured: boolean
}
```

**Drill Entity Schema:**
```
Drill {
  id: string
  coach_id: string (FK)
  sport: enum
  title: string
  description: string
  category: enum (sport-specific: forehand, backhand, serve, footwork, etc.)
  difficulty: enum (beginner, intermediate, advanced, expert)
  duration_minutes: int
  equipment_needed: array of strings
  video_urls: array of strings
  image_urls: array of strings
  steps: array of strings
  tips: array of strings
  views: int
  likes: int
  approved: boolean
}
```

**Coaching Hub Features:**
1. Find a Coach tab:
   - Grid of coach cards with photo, name, specialty, rating, rate
   - Search by name, specialty, location
   - Filter by sport, availability, rate range
   - Click coach card → Coach profile page
2. Coach profile page:
   - Header with photo, name, specialty, rating
   - Bio section
   - Experience, certifications, languages
   - Hourly rate
   - Contact buttons (email, phone, WhatsApp if available)
   - Video intro player
   - Reviews/ratings list
3. Drills library tab:
   - Grid of drill categories with icons
   - Click category → List of drills
   - Drill detail: title, description, difficulty, steps, tips, video player
4. Become a Coach form:
   - Multi-step wizard (Basic Info, Professional Details, Contact Settings)
   - Photo upload, video upload
   - Certification tags input
   - Languages multi-select

### 8. COMMUNITY FEATURES

**Forum Entity Schema:**
```
ForumPost {
  id: string
  user_id: string
  author_name: string
  title: string (null if reply)
  content: string
  sport: enum
  category: enum (general, tactics, equipment, training, tournaments)
  reply_to_post_id: string (null for main posts)
  likes: int
  created_date: timestamp
}
```

**Event Entity Schema:**
```
Event {
  id: string
  title: string
  description: string
  sport: enum
  event_type: enum (tournament, league, workshop, training_camp, social_event)
  event_date: date
  event_time: string
  end_date: date
  location: string
  address: string
  city: string
  country: string
  registration_deadline: date
  entry_fee: string
  max_participants: int
  current_participants: int
  organizer_name: string
  organizer_email: string
  organizer_phone: string
  poster_image_url: string
  status: enum (upcoming, registration_open, registration_closed, ongoing, completed)
  featured: boolean
  approved: boolean
}
```

**Sponsor Entity Schema:**
```
Sponsor {
  id: string
  company_name: string
  logo_url: string
  website_url: string
  description: string
  tier: enum (platinum, gold, silver, bronze)
  target_sports: array of enums
  contact_email: string
  active: boolean
  created_date: timestamp
}
```

**Advertisement Entity Schema:**
```
Advertisement {
  id: string
  sponsor_id: string (FK)
  campaign_id: string
  ad_title: string
  ad_content: string
  ad_image_url: string
  click_url: string
  placement: enum (
    global_footer, dashboard_sidebar, dashboard_banner,
    matches_top, opponents_sidebar, forum_banner,
    match_detail_sidebar, coaching_hub_sidebar,
    events_banner, home_hero, profile_sidebar, etc.
  )
  target_sports: array of enums (empty = all sports)
  start_date: date
  end_date: date
  clicks: int
  impressions: int
  active: boolean
  pricing_model: enum (cpm, cpc, flat_rate)
  cost_per_unit: decimal
  budget_cap: decimal
  total_spent: decimal
  priority: int (higher = more likely to show)
}
```

**Partner Entity Schema:**
```
Partner {
  id: string
  company_name: string
  logo_url: string
  website_url: string
  description: string
  partnership_type: enum (technology, content, affiliate, strategic)
  target_sports: array of enums
  promo_message: string
  landing_page: string (internal page path)
  contact_email: string
  display_order: int
  show_on_sponsors_page: boolean
  active: boolean
}
```

**SupportTicket Entity Schema:**
```
SupportTicket {
  id: string
  user_id: string (FK)
  subject: string
  message: string
  category: enum (technical, billing, account, feature_request, other)
  status: enum (open, in_progress, resolved, closed)
  priority: enum (low, medium, high, urgent)
  assigned_to: string (admin user_id)
  response: string
  created_date: timestamp
  updated_date: timestamp
}
```

**Feedback Entity Schema:**
```
Feedback {
  id: string
  user_id: string (FK)
  user_name: string
  user_email: string
  feedback_type: enum (bug, feature_request, general, compliment, complaint)
  sport: enum
  page_location: string
  message: string
  rating: int (1-5)
  status: enum (new, reviewed, addressed, dismissed)
  admin_notes: string
  created_date: timestamp
}
```

**Community Pages:**
1. Players directory: List of all users with public profiles, search/filter
2. Forum: Threaded discussions by sport and category
3. Events: Calendar and list of tournaments/events with registration
4. Messages: Direct messaging between connected players
5. Connections: Friend requests system (pending, accepted)
6. Activity Feed: Timeline of friends' matches and achievements

### 9. AI-POWERED FEATURES

**Integrate OpenAI API (or similar LLM) for:**
1. Playing Style Analysis:
   - Analyze user's match history
   - Identify patterns (aggressive/defensive, strengths/weaknesses)
   - Generate personalized recommendations
2. Opponent Analysis:
   - Given opponent profile + match history
   - Generate tactical suggestions
   - Predict effective strategies
3. Match Insights:
   - Post-match analysis
   - What worked well, what didn't
   - Improvement suggestions

**Implementation:**
- Backend Cloud Function (Firebase Functions)
- Takes user/opponent data, sends to OpenAI API with structured prompt
- Returns JSON response with insights
- Display in AI Insights page with loading states

### 10. MATCH CARD SHARING & SOCIAL FEATURES

**Shareable Match Cards:**
1. **Match Card Generator:**
   - Create visually appealing match card images
   - Include: Sport icon, player name, opponent name, final score, date, location
   - Optional "Banter Box" text field for custom messages
   - Sport-specific color theming
   - User's profile photo or avatar
   - App branding (logo watermark)

2. **Export Options:**
   - Generate PNG/JPG image (optimized for social media)
   - Include deep link QR code to match detail
   - Watermark with app logo and URL

3. **Share Destinations:**
   - Quick share buttons:
     - Facebook (with pre-filled post text)
     - Twitter/X (with hashtags like #TableTennis #MatchResult)
     - Instagram Stories (formatted correctly)
     - WhatsApp (send to contacts)
     - SMS/iMessage
   - Copy shareable link to clipboard
   - Save image to device gallery
   - Email match summary

4. **Privacy Controls:**
   - Per-match setting: "Show on profile" toggle
   - Global setting: "Allow public match sharing"
   - Option to hide opponent name on shared card
   - Admin setting to disable sharing globally

5. **Implementation:**
   - Use Flutter CustomPainter or html2canvas-like package
   - Render match card as widget
   - Convert to image using screenshot package
   - Use share_plus package for native sharing
   - Store shared match cards in Firebase Storage
   - Track share analytics (platform, count)

### 11. SUBSCRIPTION & MONETIZATION

**Subscription Tiers:**
- Free: 5 matches max, basic features
- Player Pro (£3.99/mo): Unlimited matches, advanced analytics, AI insights
- Coach Pro (£9.99/mo): Everything + coach profile, unlimited drills/resources

**Integrate with Stripe or RevenueCat:**
1. Pricing page with plan comparison cards
2. Subscribe button → Stripe checkout (web) or in-app purchase (mobile)
3. Subscription status check throughout app
4. Gate premium features with subscription checks
5. Manage subscription page (cancel, update payment method)

**Referral System:**
- Each user gets unique referral code
- Share referral link
- When friend signs up with code, both get 30 days free
- Referral dashboard showing total referrals, rewards earned

### 12. ADMIN DASHBOARD

**Admin Panel (role = "admin"):**
1. Overview tab: User count, revenue, active subscriptions, growth charts
2. Users tab: List all users, search, promote to admin, view activity
3. Coaches tab: Approve/reject coach profiles, grant featured status, manage subscriptions
4. Events tab: Approve/reject events, feature events
5. Feedback tab: View user feedback, respond, mark as resolved
6. Support tab: View support tickets, assign, respond, close tickets
7. Marketing tab: Create campaigns, track performance, manage email templates
8. Growth Analytics tab: User acquisition, retention, engagement metrics, revenue analytics
9. **Advertisements Manager:**
   - Create/edit/delete advertisements
   - Assign ads to specific placements (dashboard banner, match detail sidebar, etc.)
   - Set ad campaigns with start/end dates, target sports, budget caps
   - Track impressions, clicks, CTR for each ad
   - Link ads to sponsors
   - Ad billing dashboard with revenue tracking, invoicing
10. **Sponsors Manager:**
    - Add/edit sponsor companies with logo, website, tier (platinum/gold/silver/bronze)
    - Manage sponsor campaigns and advertisements
    - Track sponsor performance and ROI
    - Generate sponsor invoices
11. **Partners Manager:**
    - Manage partnership agreements
    - Track partner referrals and commissions
    - Featured partner sections on relevant pages
12. Featured Coaches: Manually feature coaches on homepage and coaching hub
13. Marketing Strategy: Built-in guides and templates for growth
14. Documents: Promotional materials, partnership proposals, press kits
15. Referrals: Monitor referral program performance, rewards distribution
16. Social Media: Schedule posts, track engagement, manage social templates
17. Settings tab: App configuration (name, logo, colors, default sport, app visibility, maintenance mode)

---

## UI/UX REQUIREMENTS

### Design System
**Colors by Sport:**
- Table Tennis: Green (#10B981, #059669)
- Tennis: Orange (#F97316, #EA580C)
- Badminton: Blue (#3B82F6, #2563EB)
- Squash: Red (#EF4444, #DC2626)
- Pickleball: Yellow (#EAB308, #CA8A04)

**Component Library:**
- Use Material Design or Cupertino widgets (Flutter)
- Consistent button styles (primary, secondary, outline, text)
- Card components with shadows for lists
- Bottom navigation bar for main sections (Dashboard, Matches, Opponents, Coaching, Profile)
- Floating action button for quick actions (Add Match, Add Opponent)

**Screens Hierarchy:**
1. Authentication: Login, Signup, Forgot Password
2. Onboarding: Account Type Selection, Sport Selection, Welcome Tour
3. Dashboard: Main overview
4. Matches: List, Add, Edit, Detail
5. Opponents: List, Add, Edit, Detail
6. Teams: List, Add, Edit
7. Fixtures: Calendar, List, Add
8. Coaching: Hub (Find Coach, Drills, Resources), Coach Profile, Become Coach
9. Community: Players, Forum, Events, Messages
10. Profile: View, Edit, Settings, Subscription
11. Admin: Dashboard with tabs

### Navigation
- Bottom tab bar (5 tabs): Dashboard, Matches, Add (+), Opponents, More
- Drawer menu for secondary pages (Coaching, Community, Settings, Help)
- Sport selector in app bar or drawer
- Back buttons on all detail pages

### Key Interactions
- Pull to refresh on lists
- Swipe actions (delete, edit) on list items
- Long press for context menus
- Search bars with real-time filtering
- Date pickers for date fields
- Tag input chips for strengths/weaknesses
- Color pickers for team colors
- Video upload with progress indicators
- Image cropping for profile photos

---

## DATA ARCHITECTURE

### Firebase Setup
**Firestore Collections:**
```
/users/{userId}
/matches/{matchId}
/opponents/{opponentId}
/teams/{teamId}
/fixtures/{fixtureId}
/coaches/{coachId}
/drills/{drillId}
/resources/{resourceId}
/forum_posts/{postId}
/events/{eventId}
/connections/{connectionId}
/messages/{messageId}
/subscriptions/{subscriptionId}
/referrals/{referralId}
/advertisements/{advertisementId}
/sponsors/{sponsorId}
/partners/{partnerId}
/ad_campaigns/{campaignId}
/ad_invoices/{invoiceId}
/marketing_campaigns/{campaignId}
/support_tickets/{ticketId}
/feedback/{feedbackId}
```

**Security Rules:**
- Users can read/write their own user document
- Users can only read/write matches/opponents/teams/fixtures where user_id matches
- Coach profiles readable by all, writable only by owner
- Forum posts readable by all, writable by authenticated users, deletable only by author
- Admin users (role=admin) have elevated permissions

**Indexes:**
- matches: [user_id, sport, match_date]
- opponents: [user_id, sport, name]
- fixtures: [user_id, sport, fixture_date]
- coaches: [sport, approved, featured]
- forum_posts: [sport, category, created_date]
- events: [sport, event_date, status]

### Firebase Storage
**Buckets:**
- profile_images/{userId}/
- match_videos/{matchId}/
- coach_videos/{coachId}/
- drill_media/{drillId}/
- event_posters/{eventId}/

### Cloud Functions (Backend Logic)
1. **onUserCreate**: Initialize user document with defaults
2. **onMatchCreate**: Update opponent match count, calculate win rate
3. **importFixtures**: Scrape league website, extract fixtures (if this feature is implemented)
4. **sendMatchReminder**: Daily cron job for upcoming fixtures
5. **processPayment**: Stripe webhook handler
6. **generateAIInsights**: Call OpenAI API for match analysis
7. **sendWelcomeEmail**: Email new users

---

## IMPLEMENTATION STEPS IN FLUTTERFLOW

### Phase 1: Setup & Authentication (Week 1)
1. Create FlutterFlow project
2. Enable Firebase Authentication (email/password)
3. Create User collection schema
4. Build Login, Signup, Forgot Password pages
5. Implement authentication state management
6. Build onboarding flow

### Phase 2: Core Data Models & Multi-Sport (Week 2)
1. Create Firestore collections for Match, Opponent, Team, Fixture
2. Build sport configuration data class
3. Implement sport selector with app state
4. Create reusable widgets with dynamic sport theming

### Phase 3: Match Tracking (Week 3)
1. Build Matches list page with filters
2. Create Record Match form (multi-step)
3. Implement set score entry widgets
4. Build Match detail page with video player
5. Add edit/delete functionality

### Phase 4: Opponent Management (Week 4)
1. Build Opponents list page
2. Create Add/Edit Opponent forms with tag inputs
3. Build Opponent detail page with match history
4. Implement opponent search and filtering
5. Add share opponent feature

### Phase 5: Dashboard & Analytics (Week 5)
1. Build dashboard layout with widgets
2. Implement quick stats calculations
3. Create performance charts (using charts package)
4. Build goals and achievements widgets
5. Add recent activity feed

### Phase 6: Fixtures & Teams (Week 6)
1. Build My Teams page
2. Create Add Team form with color picker
3. Implement Fixtures calendar view
4. Build Add Fixture form
5. Create upcoming fixtures widget

### Phase 7: Coaching Platform (Week 7-8)
1. Build Coaching Hub with tabs
2. Create Coach profile schema and form
3. Implement coach directory with search/filters
4. Build coach detail page
5. Create Drill and Resource schemas
6. Build drill library with categories
7. Implement drill detail page with video

### Phase 8: Community Features (Week 9)
1. Build Players directory
2. Create Forum pages (list, detail, create post)
3. Implement Events listing and detail
4. Build direct messaging interface
5. Create Connections/Friend requests system

### Phase 9: AI Features (Week 10)
1. Set up Cloud Functions
2. Integrate OpenAI API
3. Build AI Insights page
4. Implement playing style analysis
5. Create opponent analysis feature

### Phase 10: Match Sharing & Social Features (Week 11)
1. Build match card generator with CustomPainter
2. Implement image export functionality
3. Integrate share_plus for native sharing
4. Add social media quick share buttons
5. Create privacy controls for match sharing
6. Track share analytics

### Phase 11: Subscriptions & Monetization (Week 12)
1. Integrate Stripe or RevenueCat
2. Build Pricing page
3. Implement subscription checks throughout app
4. Create Manage Subscription page
5. Build referral system with tracking

### Phase 13: Admin Dashboard (Week 13-14)
1. Build admin check middleware
2. Create Admin Dashboard with tabs (Overview, Users, Coaches, Events, Feedback, Support, Marketing, Growth, Ads, Sponsors, Partners, Billing)
3. Implement user management with search, filters, role promotion
4. Build coach approval system with featured status
5. Create app settings management (visibility, branding, maintenance mode)
6. **Build Advertising Manager:**
   - Advertisement CRUD with image upload
   - Placement selector with visual preview
   - Campaign date range picker with calendar
   - Real-time impression/click tracking
   - Budget management with alerts
   - A/B testing support
   - Performance analytics dashboard
7. **Build Sponsor Management:**
   - Sponsor CRUD with logo upload
   - Tier assignment (platinum, gold, silver, bronze)
   - Sport targeting filters
   - Link sponsors to advertisements
   - Sponsor performance tracking
8. **Build Ad Billing Dashboard:**
   - Revenue tracking by sponsor and campaign
   - Automated invoice generation
   - Payment status tracking
   - Performance reports (CTR, ROI, conversions)
   - Export reports as PDF/CSV
9. **Build Partner Management:**
   - Partner CRUD with logo and promo content
   - Partnership type categorization
   - Landing page builder for partners
   - Referral tracking and commissions
10. Build feedback and support ticket management with assignment
11. Create growth analytics dashboard with charts (user acquisition, retention, revenue)
12. Marketing campaign manager with email templates

### Phase 14: Polish & Testing (Week 15-17)
1. Comprehensive testing of all features
2. UI/UX refinements
3. Performance optimization
4. Bug fixes
5. Add loading states, error handling, empty states
6. Implement analytics (Firebase Analytics)
7. Prepare for app store submission

---

## TECHNICAL SPECIFICATIONS

### State Management
Use Provider or Riverpod for:
- Current authenticated user
- Current selected sport
- App settings
- Navigation state

### Packages to Use
```yaml
dependencies:
  firebase_core: latest
  firebase_auth: latest
  cloud_firestore: latest
  firebase_storage: latest
  firebase_analytics: latest
  provider: latest
  http: latest
  cached_network_image: latest
  intl: latest
  image_picker: latest
  video_player: latest
  fl_chart: latest
  share_plus: latest
  url_launcher: latest
  flutter_stripe: latest (or revenue_cat)
  share_plus: latest
  path_provider: latest
  screenshot: latest
```

### Performance Considerations
- Lazy load lists with pagination (limit 20 per page)
- Cache images with cached_network_image
- Use StreamBuilder for real-time updates (matches, messages)
- Optimize Firestore queries with composite indexes
- Compress uploaded images before storage
- Implement offline support with Firestore persistence

### Security
- Validate all user inputs
- Sanitize text inputs to prevent XSS
- Use Firestore Security Rules to enforce permissions
- Store sensitive API keys in Cloud Functions environment
- Implement rate limiting on expensive operations

### Accessibility
- All images have alt text
- Buttons have semantic labels
- Color contrast meets WCAG AA standards
- Support screen readers
- Font scaling support

---

## TESTING REQUIREMENTS

### Unit Tests
- Data model parsing
- Business logic functions
- Calculation helpers (win rate, stats)

### Widget Tests
- Custom widget rendering
- Form validation
- Button interactions

### Integration Tests
- Authentication flow
- Match creation flow
- Opponent management flow
- Coach profile creation

---

## DEPLOYMENT

### iOS
1. Apple Developer Account
2. Configure bundle ID
3. Set up App Store Connect
4. Upload build via Xcode or CI/CD
5. Submit for review

### Android
1. Google Play Console account
2. Configure app signing
3. Generate release build
4. Upload to Play Console
5. Submit for review

### Web (optional)
1. Configure Firebase Hosting
2. Build web version
3. Deploy to Firebase Hosting

---

## ADDITIONAL NOTES

**Localization:**
Support multiple languages (English, Spanish, French, German). Use Flutter's internationalization (i18n) with ARB files.

**Onboarding:**
First-time users see:
1. Welcome screen with app overview
2. Account type selection (Player/Coach)
3. Sport selection
4. Quick tour of main features

**Push Notifications:**
- Match reminders (24h before fixture)
- New messages
- Connection requests
- Coach review requests
- Achievement unlocks

**Analytics Events to Track:**
- User signup
- Match recorded
- Opponent added
- Coach profile viewed
- Drill viewed
- Subscription started
- Referral completed
- Match card shared (track platform)
- Ad impression
- Ad click
- Partner link clicked

**Error Handling:**
- Show user-friendly error messages
- Log errors to Firebase Crashlytics
- Retry failed operations with exponential backoff
- Offline mode with sync when back online

---

## DELIVERABLES

1. Fully functional mobile app (iOS & Android)
2. Web version (optional)
3. Admin dashboard accessible via web
4. Complete Firestore data structure
5. Cloud Functions for backend logic
6. Stripe integration for subscriptions
7. OpenAI integration for AI features
8. User documentation
9. App store assets (screenshots, descriptions)

---

## SUCCESS METRICS

- App Store rating: 4.5+ stars
- User retention: 60%+ after 30 days
- Subscription conversion: 10%+ of free users
- Average session duration: 5+ minutes
- Crash-free rate: 99.5%+

---

This specification provides everything needed to rebuild MatchPlay Pro AI in FlutterFlow. Follow the phased implementation plan, focusing on core features first (authentication, match tracking, opponent management) before moving to advanced features (AI, coaching, community, advertising). Prioritize mobile-first design with smooth animations and intuitive navigation.

---

## KEY FEATURES CHECKLIST

✅ **Core Functionality:**
- Multi-sport architecture (5 sports)
- Match tracking with set-by-set scoring
- Opponent intelligence profiles
- Team and fixture management
- Dashboard with analytics

✅ **Social & Sharing:**
- Shareable match cards with images
- Social media integration (Facebook, Twitter, Instagram, WhatsApp)
- Banter Box for custom messages
- Privacy controls for sharing
- Public player profiles

✅ **Coaching Platform:**
- Coach profiles and directory
- Drill library by category
- Resource center
- Video tutorials
- Booking and session management

✅ **Community:**
- Player directory
- Forum discussions
- Events calendar
- Direct messaging
- Friend connections

✅ **AI Features:**
- Playing style analysis
- Opponent analysis
- Match insights
- Tactical recommendations

✅ **Monetization:**
- 3 subscription tiers
- Stripe integration
- Referral program
- In-app purchases

✅ **Admin Dashboard:**
- User management
- Coach approval
- Event approval
- **Advertisement Manager** (create, track, bill)
- **Sponsor Manager** (logos, tiers, campaigns)
- **Ad Billing Dashboard** (revenue, invoices, ROI)
- **Partner Management** (partnerships, commissions)
- Feedback & support tickets
- Growth analytics
- Marketing campaigns
- App settings

✅ **Performance:**
- Offline support
- Image caching
- Query optimization
- Analytics tracking
- Share event monitoring
17 Weeks
Estimated Timeline
30+
Database Collections
50+
Screens to Build
5
Sports Supported
📱 Core Features
  • • Authentication & User Management
  • • Multi-Sport Architecture
  • • Match Tracking System
  • • Opponent Intelligence
  • • Fixtures & Team Management
🎨 UI/UX Requirements
  • • Sport-Specific Color Themes
  • • Material Design Components
  • • Bottom Navigation
  • • Responsive Layouts
  • • Dark Mode Support
🔥 Firebase Setup
  • • Firestore Collections
  • • Security Rules
  • • Cloud Storage
  • • Cloud Functions
  • • Analytics & Crashlytics
🤖 AI Integration
  • • OpenAI API Integration
  • • Playing Style Analysis
  • • Opponent Analysis
  • • Match Insights
  • • Tactical Recommendations
💰 Monetization
  • • Stripe Integration
  • • 3 Subscription Tiers
  • • In-App Purchases
  • • Referral System
  • • Revenue Tracking
🎓 Coaching Platform
  • • Coach Profiles
  • • Drill Library
  • • Resource Center
  • • Video Tutorials
  • • Booking System
💡 Implementation Notes for AI Assistant

Using This Prompt

Copy the entire prompt above and paste it into your conversation with an AI assistant (ChatGPT, Claude, etc.) when working in FlutterFlow. The AI will have complete context about the app's structure, features, and requirements.

Phased Approach

The specification includes a 17-week phased implementation plan. Start with core features (authentication, match tracking, opponent management) before moving to advanced features (AI, coaching, community, advertising).

Critical Differences from Base44

  • • FlutterFlow uses Firebase (Firestore) instead of Base44's entity system
  • • Mobile-first architecture vs web-first
  • • State management with Provider/Riverpod instead of React Query
  • • Flutter widgets instead of React components
  • • Cloud Functions for backend instead of Deno Deploy

What's Included

  • ✅ Complete feature specifications
  • ✅ Database schemas for all 30+ entities
  • ✅ UI/UX requirements with sport-specific theming
  • ✅ Firebase setup instructions
  • ✅ Step-by-step implementation phases
  • ✅ Integration requirements (Stripe, OpenAI)
  • ✅ Security and performance considerations
  • ✅ Testing requirements
  • ✅ Deployment checklist