# BuyerKiosk Live - Xamarin to Flutter Migration Plan

## Executive Summary

This document outlines a comprehensive plan to migrate the BuyerKiosk Live mobile application from Xamarin.Forms to Flutter. The existing app is a retail management tool that displays real-time store metrics, manages buyer queues, tracks completed transactions, monitors buyer performance, and handles shift notes/tasks.

---

## 1. Current Application Analysis

### 1.1 Architecture Overview
- **Pattern**: MVVM (Model-View-ViewModel)
- **Platform**: Xamarin.Forms (.NET Standard 2.0)
- **Targets**: iOS 16.0+ and Android API 13+

### 1.2 Core Features
| Feature | Description |
|---------|-------------|
| Dashboard | Multi-store overview with live metrics (sales, buys, queue, staff) |
| Store Details | Drill-down metrics with navigation to sub-features |
| Buy Queue | Real-time customer queue with buyer assignments |
| Completed Buys | Historical transaction records with processing times |
| Buyer Stats | Per-buyer performance metrics and productivity |
| Shift Notes/Tasks | Date-filtered messages and actionable tasks with status tracking |
| Installation | API key validation and secure storage |

### 1.3 Current Tech Stack
| Component | Technology |
|-----------|------------|
| UI Framework | Xamarin.Forms 5.0 |
| JSON | Newtonsoft.Json 13.0.3 |
| Secure Storage | sameerIOTApps.Plugin.SecureStorage 2.5.0 |
| Dialogs | Acr.UserDialogs 7.2.0 |
| Popups | Rg.Plugins.Popup 2.1.0 |
| Real-time | Ably.io 1.2.14 |

### 1.4 API Endpoints
| Endpoint | Action | Purpose |
|----------|--------|---------|
| `mobile.php` | dashboard | Get all stores with metrics |
| `mobile.php` | storePage | Get single store details |
| `mobile.php` | currentQueue | Get buy queue |
| `mobile.php` | completedBuys | Get completed purchases |
| `mobile.php` | buyerStats | Get buyer performance |
| `drs/{typeNum}/shiftNotes/*` | Various | CRUD for shift notes |

---

## 2. Flutter Project Architecture

### 2.1 Recommended Architecture: Clean Architecture with Riverpod

```
lib/
├── main.dart
├── app.dart
├── core/
│   ├── constants/
│   │   ├── api_constants.dart
│   │   ├── app_colors.dart
│   │   ├── app_strings.dart
│   │   └── app_dimensions.dart
│   ├── errors/
│   │   ├── exceptions.dart
│   │   └── failures.dart
│   ├── network/
│   │   ├── api_client.dart
│   │   ├── api_interceptors.dart
│   │   └── network_info.dart
│   ├── theme/
│   │   ├── app_theme.dart
│   │   └── text_styles.dart
│   └── utils/
│       ├── date_utils.dart
│       ├── currency_utils.dart
│       └── hash_utils.dart
├── data/
│   ├── datasources/
│   │   ├── remote/
│   │   │   ├── dashboard_remote_datasource.dart
│   │   │   ├── store_remote_datasource.dart
│   │   │   ├── queue_remote_datasource.dart
│   │   │   └── shift_notes_remote_datasource.dart
│   │   └── local/
│   │       └── secure_storage_datasource.dart
│   ├── models/
│   │   ├── store_model.dart
│   │   ├── store_detail_model.dart
│   │   ├── queue_item_model.dart
│   │   ├── completed_buy_model.dart
│   │   ├── buyer_stats_model.dart
│   │   └── shift_note_model.dart
│   └── repositories/
│       ├── dashboard_repository_impl.dart
│       ├── store_repository_impl.dart
│       ├── queue_repository_impl.dart
│       └── shift_notes_repository_impl.dart
├── domain/
│   ├── entities/
│   │   ├── store.dart
│   │   ├── store_detail.dart
│   │   ├── queue_item.dart
│   │   ├── completed_buy.dart
│   │   ├── buyer_stats.dart
│   │   └── shift_note.dart
│   ├── repositories/
│   │   ├── dashboard_repository.dart
│   │   ├── store_repository.dart
│   │   ├── queue_repository.dart
│   │   └── shift_notes_repository.dart
│   └── usecases/
│       ├── get_dashboard.dart
│       ├── get_store_details.dart
│       ├── get_queue.dart
│       ├── get_completed_buys.dart
│       ├── get_buyer_stats.dart
│       └── shift_notes/
│           ├── get_shift_notes.dart
│           ├── create_shift_note.dart
│           ├── update_shift_note.dart
│           └── delete_shift_note.dart
├── presentation/
│   ├── providers/
│   │   ├── auth_provider.dart
│   │   ├── dashboard_provider.dart
│   │   ├── store_detail_provider.dart
│   │   ├── queue_provider.dart
│   │   ├── completed_buys_provider.dart
│   │   ├── buyer_stats_provider.dart
│   │   └── shift_notes_provider.dart
│   ├── screens/
│   │   ├── installation/
│   │   │   └── installation_screen.dart
│   │   ├── dashboard/
│   │   │   └── dashboard_screen.dart
│   │   ├── store_detail/
│   │   │   └── store_detail_screen.dart
│   │   ├── queue/
│   │   │   └── buy_queue_screen.dart
│   │   ├── completed/
│   │   │   └── completed_buys_screen.dart
│   │   ├── stats/
│   │   │   └── buyer_stats_screen.dart
│   │   └── shift_notes/
│   │       ├── shift_notes_screen.dart
│   │       ├── shift_note_detail_screen.dart
│   │       └── task_creation_screen.dart
│   └── widgets/
│       ├── common/
│       │   ├── loading_indicator.dart
│       │   ├── error_widget.dart
│       │   ├── empty_state.dart
│       │   └── pull_to_refresh.dart
│       ├── cards/
│       │   ├── store_card.dart
│       │   ├── queue_item_card.dart
│       │   ├── completed_buy_card.dart
│       │   ├── buyer_stats_card.dart
│       │   └── shift_note_card.dart
│       ├── charts/
│       │   ├── sales_chart.dart
│       │   ├── performance_chart.dart
│       │   └── queue_chart.dart
│       └── dialogs/
│           ├── confirmation_dialog.dart
│           └── shift_note_popup.dart
└── router/
    └── app_router.dart
```

---

## 3. Recommended Flutter Packages

### 3.1 UI Component Library

**Primary Choice: `shadcn_flutter`** (or `forui`)
```yaml
dependencies:
  shadcn_flutter: ^0.17.0  # Modern, customizable UI components
```

**Alternative: Material Design 3 (built-in)**
Flutter's Material 3 is excellent out of the box and may be sufficient.

### 3.2 Complete Package List

```yaml
dependencies:
  flutter:
    sdk: flutter

  # ===== STATE MANAGEMENT =====
  flutter_riverpod: ^2.5.1        # Reactive state management
  riverpod_annotation: ^2.3.5     # Code generation for Riverpod

  # ===== NETWORKING =====
  dio: ^5.4.3                     # HTTP client with interceptors
  retrofit: ^4.1.0                # Type-safe API calls
  connectivity_plus: ^6.0.3       # Network connectivity checking

  # ===== LOCAL STORAGE =====
  flutter_secure_storage: ^9.0.0  # Secure storage for API key
  shared_preferences: ^2.2.3      # Simple key-value storage

  # ===== NAVIGATION =====
  go_router: ^14.2.0              # Declarative routing

  # ===== UI COMPONENTS =====
  shadcn_flutter: ^0.17.0         # Modern UI component library
  # OR use these alternatives:
  # forui: ^0.5.0                 # Minimal UI components

  # ===== CHARTS & VISUALIZATION =====
  fl_chart: ^0.68.0               # Beautiful, animated charts
  syncfusion_flutter_charts: ^25.1.37  # Enterprise-grade charts (free tier)

  # ===== DIALOGS & POPUPS =====
  flutter_easyloading: ^3.0.5     # Loading dialogs
  toastification: ^2.0.0          # Toast notifications
  modal_bottom_sheet: ^3.0.0      # Bottom sheet modals

  # ===== DATE/TIME =====
  intl: ^0.19.0                   # Date formatting & i18n
  table_calendar: ^3.1.1          # Calendar widget (if needed)

  # ===== FORMS & VALIDATION =====
  reactive_forms: ^17.0.1         # Reactive form handling
  # OR
  flutter_form_builder: ^9.2.1    # Form building with validation

  # ===== UTILITIES =====
  freezed_annotation: ^2.4.1      # Immutable data classes
  json_annotation: ^4.8.1         # JSON serialization
  equatable: ^2.0.5               # Value equality
  uuid: ^4.4.0                    # UUID generation
  crypto: ^3.0.3                  # SHA512 hashing

  # ===== REAL-TIME (if using Ably) =====
  ably_flutter: ^1.2.33           # Ably real-time messaging

  # ===== PULL TO REFRESH =====
  pull_to_refresh: ^2.0.0         # Enhanced pull-to-refresh

  # ===== IMAGE CACHING =====
  cached_network_image: ^3.3.1    # Image caching
  flutter_svg: ^2.0.10            # SVG support

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^4.0.0

  # ===== CODE GENERATION =====
  build_runner: ^2.4.9
  freezed: ^2.5.2
  json_serializable: ^6.7.1
  retrofit_generator: ^8.1.0
  riverpod_generator: ^2.4.0

  # ===== TESTING =====
  mockito: ^5.4.4
  mocktail: ^1.0.3
```

### 3.3 Package Selection Rationale

| Category | Package | Why This Choice |
|----------|---------|-----------------|
| State Management | `flutter_riverpod` | Compile-time safety, excellent DevTools, replaces global variables pattern |
| HTTP Client | `dio` + `retrofit` | Interceptors for auth, type-safe API calls, better than raw http |
| Charts | `fl_chart` | Beautiful animations, customizable, active maintenance |
| Secure Storage | `flutter_secure_storage` | Direct replacement for Xamarin SecureStorage |
| Navigation | `go_router` | Deep linking, type-safe routes, official Flutter package |
| Loading Dialogs | `flutter_easyloading` | Drop-in replacement for Acr.UserDialogs |
| Data Classes | `freezed` | Immutable, copyWith, JSON serialization |

---

## 4. Screen-by-Screen Migration Map

### 4.1 Installation Screen
**Xamarin**: `InstallationPage.xaml` + `InstallationViewModel.cs`
**Flutter**: `lib/presentation/screens/installation/installation_screen.dart`

```dart
// Key components to implement:
// - API key text field (auto-uppercase)
// - Validation logic with API call
// - Secure storage of valid key
// - Navigation to dashboard on success
```

**Widgets needed**:
- Text input with uppercase formatter
- Validate button with loading state
- Error message display

---

### 4.2 Dashboard Screen
**Xamarin**: `DashboardPage.xaml` + `DashboardViewModel.cs`
**Flutter**: `lib/presentation/screens/dashboard/dashboard_screen.dart`

```dart
// Key components to implement:
// - ListView of store cards
// - Pull-to-refresh
// - Store logo based on type (PC/OU/CM/SE/PA)
// - Metrics display (sales goal, buys goal, queue, wait time)
// - 6-tap logo for debug API clear
// - Navigation to store detail
```

**Widgets needed**:
- `StoreCard` - Displays store metrics with logo
- Charts showing sales/buys progress (optional enhancement)

**Charts opportunity**: Add progress indicators or mini charts for goals

---

### 4.3 Store Detail Screen
**Xamarin**: `StoreDetailPage.xaml` + `StoreDetailViewModel.cs`
**Flutter**: `lib/presentation/screens/store_detail/store_detail_screen.dart`

```dart
// Key components to implement:
// - Header with store name and metrics
// - Total buys, queue count, completed count
// - Average process time display
// - Navigation buttons to sub-screens
// - Pull-to-refresh
```

**Widgets needed**:
- Metric cards with icons
- Navigation button grid

**Charts opportunity**: Add performance trend chart

---

### 4.4 Buy Queue Screen
**Xamarin**: `BuyQueuePage.xaml` + `BuyQueueViewModel.cs`
**Flutter**: `lib/presentation/screens/queue/buy_queue_screen.dart`

```dart
// Key components to implement:
// - ListView of queue items
// - Customer name, buyer name, container counts
// - Wait time formatting (XHR YM)
// - In-store indicator
// - Pull-to-refresh
```

**Widgets needed**:
- `QueueItemCard` - Customer queue card with progress

---

### 4.5 Completed Buys Screen
**Xamarin**: `CompletedBuyPage.xaml` + `CompletedBuyViewModel.cs`
**Flutter**: `lib/presentation/screens/completed/completed_buys_screen.dart`

```dart
// Key components to implement:
// - ListView of completed transactions
// - Customer name, buyer name, containers
// - Time completed, process time
// - Pull-to-refresh
```

**Widgets needed**:
- `CompletedBuyCard` - Transaction summary card

---

### 4.6 Buyer Stats Screen
**Xamarin**: `BuyerStatsPage.xaml` + `BuyerStatsViewModel.cs`
**Flutter**: `lib/presentation/screens/stats/buyer_stats_screen.dart`

```dart
// Key components to implement:
// - ListView of buyer performance
// - Buyer name, number of buys, bins processed
// - Average process time, avg time per bin
// - Pull-to-refresh
```

**Widgets needed**:
- `BuyerStatsCard` - Performance metrics card

**Charts opportunity**: Bar chart comparing buyer performance

---

### 4.7 Shift Notes Screen
**Xamarin**: `ShiftNotesPage.xaml` + `ShiftNotesViewModel.cs`
**Flutter**: `lib/presentation/screens/shift_notes/shift_notes_screen.dart`

```dart
// Key components to implement:
// - Toggle between Messages and Tasks
// - Date range picker
// - ListView with priority icons
// - Tap to open detail popup
// - Add button navigation
// - Pull-to-refresh with load more
```

**Widgets needed**:
- `ShiftNoteCard` - Note/task card with priority indicator
- Date range selector
- Toggle switch for Messages/Tasks

---

### 4.8 Shift Note Detail Popup
**Xamarin**: `ShiftNotesPopupPage.xaml` (Rg.Plugins.Popup)
**Flutter**: `lib/presentation/widgets/dialogs/shift_note_popup.dart`

```dart
// Key components to implement:
// - Modal bottom sheet or dialog
// - Title, comment, dates display
// - Status change button (for tasks)
// - Delete button with confirmation
// - Priority display
```

**Implementation**: Use `showModalBottomSheet` or custom dialog

---

### 4.9 Task Creation Screen
**Xamarin**: `TaskCreationPage.xaml` + `TaskCreationViewModel.cs`
**Flutter**: `lib/presentation/screens/shift_notes/task_creation_screen.dart`

```dart
// Key components to implement:
// - Dynamic form (Message vs Task mode)
// - Title and comment fields
// - Priority picker (Tasks only)
// - Date pickers (Tasks only)
// - Submitter name field
// - Submit/Cancel buttons
// - Hash ID generation
```

**Widgets needed**:
- Form with reactive validation
- Priority selector
- Date pickers

---

## 5. Data Models

### 5.1 Entity Definitions (using Freezed)

```dart
// lib/domain/entities/store.dart
@freezed
class Store with _$Store {
  const factory Store({
    required String typeNum,
    required String storeName,
    required int numBuyers,
    required int numSorters,
    required int inQueue,
    required double salesGoal,
    required double salesActual,
    required double buysGoal,
    required double buysActual,
    required int waitTime,
  }) = _Store;
}

// lib/domain/entities/queue_item.dart
@freezed
class QueueItem with _$QueueItem {
  const factory QueueItem({
    required String customerName,
    required String buyerName,
    required int numContainers,
    required int processedContainers,
    required int waitTime,
    required bool inStore,
  }) = _QueueItem;
}

// lib/domain/entities/shift_note.dart
@freezed
class ShiftNote with _$ShiftNote {
  const factory ShiftNote({
    required String id,
    required String title,
    required String comment,
    required ShiftNoteType type,
    required ShiftNoteStatus status,
    required ShiftNotePriority priority,
    required String submitter,
    required DateTime startDate,
    required DateTime endDate,
    required DateTime createdAt,
  }) = _ShiftNote;
}

enum ShiftNoteType { message, task }
enum ShiftNoteStatus { open, inProgress, closed }
enum ShiftNotePriority { none, low, medium, high }
```

---

## 6. API Integration

### 6.1 API Client Setup with Dio

```dart
// lib/core/network/api_client.dart
class ApiClient {
  late final Dio _dio;

  ApiClient() {
    _dio = Dio(BaseOptions(
      baseUrl: 'https://buyerkiosk.com/api/',
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
    ));

    _dio.interceptors.addAll([
      AuthInterceptor(),
      LogInterceptor(),
      ErrorInterceptor(),
    ]);
  }
}

// lib/core/network/api_interceptors.dart
class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    final storage = FlutterSecureStorage();
    final apiKey = await storage.read(key: 'APItoken');
    if (apiKey != null) {
      options.data ??= {};
      if (options.data is Map) {
        options.data['APIKey'] = apiKey;
      }
    }
    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 403) {
      // Clear stored API key on 403
      final storage = FlutterSecureStorage();
      await storage.delete(key: 'APItoken');
    }
    handler.next(err);
  }
}
```

### 6.2 Retrofit API Definitions

```dart
// lib/data/datasources/remote/dashboard_api.dart
@RestApi()
abstract class DashboardApi {
  factory DashboardApi(Dio dio) = _DashboardApi;

  @POST('mobile.php')
  @FormUrlEncoded()
  Future<List<StoreModel>> getDashboard(
    @Field('APIKey') String apiKey,
    @Field('action') String action,
  );

  @POST('mobile.php')
  @FormUrlEncoded()
  Future<StoreDetailModel> getStoreDetail(
    @Field('APIKey') String apiKey,
    @Field('action') String action,
    @Field('store') String storeTypeNum,
  );
}
```

---

## 7. State Management with Riverpod

### 7.1 Provider Examples

```dart
// lib/presentation/providers/dashboard_provider.dart
@riverpod
class DashboardNotifier extends _$DashboardNotifier {
  @override
  FutureOr<List<Store>> build() async {
    return _fetchDashboard();
  }

  Future<List<Store>> _fetchDashboard() async {
    final repository = ref.read(dashboardRepositoryProvider);
    return repository.getDashboard();
  }

  Future<void> refresh() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_fetchDashboard);
  }
}

// lib/presentation/providers/auth_provider.dart
@riverpod
class AuthNotifier extends _$AuthNotifier {
  @override
  FutureOr<bool> build() async {
    return _checkInstallation();
  }

  Future<bool> _checkInstallation() async {
    final storage = ref.read(secureStorageProvider);
    final apiKey = await storage.read(key: 'APItoken');
    return apiKey != null;
  }

  Future<bool> validateAndStoreApiKey(String apiKey) async {
    // Validate by making test API call
    // Store on success
    // Return result
  }

  Future<void> clearApiKey() async {
    final storage = ref.read(secureStorageProvider);
    await storage.delete(key: 'APItoken');
    state = const AsyncData(false);
  }
}
```

---

## 8. Navigation with GoRouter

```dart
// lib/router/app_router.dart
final routerProvider = Provider<GoRouter>((ref) {
  final authState = ref.watch(authNotifierProvider);

  return GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      final isInstalled = authState.valueOrNull ?? false;
      final isInstallingRoute = state.matchedLocation == '/install';

      if (!isInstalled && !isInstallingRoute) {
        return '/install';
      }
      if (isInstalled && isInstallingRoute) {
        return '/';
      }
      return null;
    },
    routes: [
      GoRoute(
        path: '/install',
        builder: (context, state) => const InstallationScreen(),
      ),
      GoRoute(
        path: '/',
        builder: (context, state) => const DashboardScreen(),
        routes: [
          GoRoute(
            path: 'store/:typeNum',
            builder: (context, state) => StoreDetailScreen(
              typeNum: state.pathParameters['typeNum']!,
            ),
            routes: [
              GoRoute(
                path: 'queue',
                builder: (context, state) => BuyQueueScreen(
                  typeNum: state.pathParameters['typeNum']!,
                ),
              ),
              GoRoute(
                path: 'completed',
                builder: (context, state) => CompletedBuysScreen(
                  typeNum: state.pathParameters['typeNum']!,
                ),
              ),
              GoRoute(
                path: 'stats',
                builder: (context, state) => BuyerStatsScreen(
                  typeNum: state.pathParameters['typeNum']!,
                ),
              ),
              GoRoute(
                path: 'notes',
                builder: (context, state) => ShiftNotesScreen(
                  typeNum: state.pathParameters['typeNum']!,
                ),
              ),
              GoRoute(
                path: 'notes/create',
                builder: (context, state) => TaskCreationScreen(
                  typeNum: state.pathParameters['typeNum']!,
                ),
              ),
            ],
          ),
        ],
      ),
    ],
  );
});
```

---

## 9. Charts Implementation

### 9.1 Sales/Buys Goal Progress Chart

```dart
// lib/presentation/widgets/charts/goal_progress_chart.dart
import 'package:fl_chart/fl_chart.dart';

class GoalProgressChart extends StatelessWidget {
  final double actual;
  final double goal;
  final String label;
  final Color color;

  @override
  Widget build(BuildContext context) {
    final percentage = goal > 0 ? (actual / goal).clamp(0.0, 1.0) : 0.0;

    return SizedBox(
      height: 100,
      width: 100,
      child: Stack(
        alignment: Alignment.center,
        children: [
          PieChart(
            PieChartData(
              sectionsSpace: 0,
              centerSpaceRadius: 35,
              sections: [
                PieChartSectionData(
                  value: percentage * 100,
                  color: color,
                  radius: 10,
                  showTitle: false,
                ),
                PieChartSectionData(
                  value: (1 - percentage) * 100,
                  color: Colors.grey.shade200,
                  radius: 10,
                  showTitle: false,
                ),
              ],
            ),
          ),
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '${(percentage * 100).toInt()}%',
                style: Theme.of(context).textTheme.titleMedium,
              ),
              Text(label, style: Theme.of(context).textTheme.bodySmall),
            ],
          ),
        ],
      ),
    );
  }
}
```

### 9.2 Buyer Performance Bar Chart

```dart
// lib/presentation/widgets/charts/buyer_performance_chart.dart
class BuyerPerformanceChart extends StatelessWidget {
  final List<BuyerStats> stats;

  @override
  Widget build(BuildContext context) {
    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.spaceAround,
        maxY: stats.map((s) => s.numBuys.toDouble()).reduce(max) * 1.2,
        titlesData: FlTitlesData(
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                final index = value.toInt();
                if (index >= 0 && index < stats.length) {
                  return Text(
                    stats[index].buyerName.split(' ').first,
                    style: const TextStyle(fontSize: 10),
                  );
                }
                return const SizedBox.shrink();
              },
            ),
          ),
        ),
        barGroups: stats.asMap().entries.map((entry) {
          return BarChartGroupData(
            x: entry.key,
            barRods: [
              BarChartRodData(
                toY: entry.value.numBuys.toDouble(),
                color: Theme.of(context).primaryColor,
                width: 20,
                borderRadius: BorderRadius.circular(4),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
}
```

---

## 10. Implementation Phases

### Phase 1: Project Setup & Core Infrastructure (Week 1)
- [ ] Initialize Flutter project with recommended folder structure
- [ ] Configure pubspec.yaml with all dependencies
- [ ] Set up Dio client with interceptors
- [ ] Implement secure storage service
- [ ] Create base theme and styling
- [ ] Set up Riverpod providers infrastructure
- [ ] Configure GoRouter navigation
- [ ] Create common widgets (loading, error, empty states)

### Phase 2: Authentication & Installation (Week 1)
- [ ] Create Installation screen UI
- [ ] Implement API key validation logic
- [ ] Set up auth state management
- [ ] Add navigation guards for unauthenticated users
- [ ] Test API connection and storage

### Phase 3: Dashboard & Store Detail (Week 2)
- [ ] Create Store entity and model with Freezed
- [ ] Implement dashboard API integration
- [ ] Build Dashboard screen with store cards
- [ ] Add pull-to-refresh functionality
- [ ] Implement 6-tap debug feature
- [ ] Create Store Detail screen
- [ ] Build navigation to sub-features
- [ ] Add goal progress charts (enhancement)

### Phase 4: Queue & Completed Buys (Week 2)
- [ ] Create QueueItem and CompletedBuy entities
- [ ] Implement queue and completed buys API calls
- [ ] Build Buy Queue screen with list
- [ ] Build Completed Buys screen
- [ ] Add wait time formatting utilities
- [ ] Implement pull-to-refresh on both screens

### Phase 5: Buyer Stats (Week 3)
- [ ] Create BuyerStats entity
- [ ] Implement buyer stats API call
- [ ] Build Buyer Stats screen
- [ ] Add performance comparison chart (enhancement)
- [ ] Implement pull-to-refresh

### Phase 6: Shift Notes/Tasks (Week 3-4)
- [ ] Create ShiftNote entity with enums
- [ ] Implement all shift notes API calls (CRUD)
- [ ] Build Shift Notes list screen
- [ ] Implement date range picker
- [ ] Add Messages/Tasks toggle
- [ ] Create Shift Note detail popup/modal
- [ ] Build Task Creation form screen
- [ ] Implement priority selector
- [ ] Add hash ID generation utility
- [ ] Implement delete confirmation
- [ ] Add status change functionality

### Phase 7: Polish & Testing (Week 4)
- [ ] Add loading states throughout app
- [ ] Implement error handling and display
- [ ] Add empty state illustrations
- [ ] Write unit tests for use cases
- [ ] Write widget tests for key screens
- [ ] Write integration tests for navigation
- [ ] Performance optimization
- [ ] iOS-specific adjustments
- [ ] Android-specific adjustments

### Phase 8: Deployment Preparation (Week 5)
- [ ] Configure app icons and splash screens
- [ ] Set up iOS certificates and provisioning
- [ ] Set up Android keystore
- [ ] Configure build flavors (dev/prod)
- [ ] Test on physical devices
- [ ] Prepare store listings
- [ ] Beta testing
- [ ] Production release

---

## 11. Migration Considerations

### 11.1 Breaking Changes from Xamarin

| Xamarin Behavior | Flutter Equivalent |
|------------------|-------------------|
| App.GlobalVariables | Riverpod providers (StateNotifier) |
| MessagingCenter | Riverpod ref.listen or callbacks |
| INotifyPropertyChanged | StateNotifier/ChangeNotifier |
| XAML bindings | Widget build with ref.watch |
| Custom Renderers | Not needed (Flutter has consistent styling) |
| Platform-specific projects | Single codebase (platform channels if needed) |

### 11.2 Data Migration
- No local database to migrate
- API key will need to be re-entered on first Flutter app launch
- No user data stored locally beyond API key

### 11.3 API Compatibility
- No backend changes required
- Same endpoints work with Flutter client
- Consider adding client version header for analytics

---

## 12. Testing Strategy

### 12.1 Unit Tests
```dart
// test/domain/usecases/get_dashboard_test.dart
void main() {
  group('GetDashboard', () {
    test('should return list of stores from repository', () async {
      // Arrange
      final mockRepository = MockDashboardRepository();
      when(() => mockRepository.getDashboard())
          .thenAnswer((_) async => [testStore]);

      final usecase = GetDashboard(mockRepository);

      // Act
      final result = await usecase();

      // Assert
      expect(result, [testStore]);
      verify(() => mockRepository.getDashboard()).called(1);
    });
  });
}
```

### 12.2 Widget Tests
```dart
// test/presentation/widgets/store_card_test.dart
void main() {
  testWidgets('StoreCard displays store information', (tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: StoreCard(store: testStore),
      ),
    );

    expect(find.text('Test Store'), findsOneWidget);
    expect(find.text('5 in queue'), findsOneWidget);
  });
}
```

### 12.3 Integration Tests
```dart
// integration_test/app_test.dart
void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('Full app flow', (tester) async {
    app.main();
    await tester.pumpAndSettle();

    // Verify installation screen
    expect(find.byType(InstallationScreen), findsOneWidget);

    // Enter API key
    await tester.enterText(find.byType(TextField), 'TEST_API_KEY');
    await tester.tap(find.text('Validate'));
    await tester.pumpAndSettle();

    // Verify dashboard
    expect(find.byType(DashboardScreen), findsOneWidget);
  });
}
```

---

## 13. Performance Optimizations

### 13.1 List Performance
- Use `ListView.builder` for all lists (already default behavior)
- Implement proper `key` usage for list items
- Consider `Sliver` widgets for complex scrolling

### 13.2 State Management
- Use `select` to watch only needed state portions
- Implement proper `autoDispose` for providers
- Cache API responses appropriately

### 13.3 Image Optimization
- Use `cached_network_image` for network images
- Preload critical images
- Use appropriate image resolutions

---

## 14. Accessibility

- Add semantic labels to all interactive elements
- Ensure proper contrast ratios
- Support dynamic text sizing
- Test with screen readers (TalkBack/VoiceOver)

---

## 15. Monitoring & Analytics (Optional Enhancements)

Consider adding:
- Firebase Analytics for usage tracking
- Crashlytics for error reporting
- Performance monitoring

---

## 16. Files to Create First

1. `pubspec.yaml` - Dependencies
2. `lib/main.dart` - App entry
3. `lib/app.dart` - MaterialApp setup
4. `lib/core/constants/api_constants.dart` - API URLs
5. `lib/core/network/api_client.dart` - Dio setup
6. `lib/data/datasources/local/secure_storage_datasource.dart` - Storage
7. `lib/presentation/providers/auth_provider.dart` - Auth state
8. `lib/router/app_router.dart` - Navigation
9. `lib/presentation/screens/installation/installation_screen.dart` - First screen
10. `lib/presentation/screens/dashboard/dashboard_screen.dart` - Main screen

---

## Summary

This migration plan provides a complete roadmap for converting the BuyerKiosk Live app from Xamarin.Forms to Flutter. The new architecture uses:

- **Clean Architecture** for maintainability
- **Riverpod** for reactive state management
- **Dio + Retrofit** for type-safe API calls
- **GoRouter** for declarative navigation
- **fl_chart** for data visualization
- **Freezed** for immutable data models
- **flutter_secure_storage** for API key storage

The Flutter app will be more maintainable, performant, and easier to extend with new features. The estimated timeline is 4-5 weeks for a complete migration with testing.
