# BuyerKiosk Live - Navigation Guide

This document provides a comprehensive guide to the navigation structure and implementation in the BuyerKiosk Live Flutter application.

## Overview

The app uses **GoRouter** with **Riverpod** for declarative, type-safe navigation with state management integration.

## Architecture

### Key Files

1. **`lib/main.dart`** - Application entry point
   - Initializes Flutter bindings
   - Configures EasyLoading
   - Wraps app with ProviderScope
   - Sets system UI overlay style

2. **`lib/app.dart`** - Main app widget
   - Configures MaterialApp.router
   - Applies custom theme
   - Integrates EasyLoading builder

3. **`lib/router/app_router.dart`** - Router configuration
   - Defines all routes
   - Implements authentication redirects
   - Provides navigation helper extensions
   - Contains placeholder screens (replace with actual screens)

## Route Structure

```
┌─────────────────────────────────────────────────────────────────┐
│                         Root (/)                                │
│                    DashboardScreen                              │
│                  (List of stores)                               │
└─────────────────────────┬───────────────────────────────────────┘
                          │
         ┌────────────────┼────────────────┐
         │                │                │
         ▼                ▼                ▼
    /install         /store/:typeNum   [Other routes]
 InstallationScreen  StoreDetailScreen
                          │
         ┌────────────────┼────────────────┬─────────────┐
         │                │                │             │
         ▼                ▼                ▼             ▼
    queue/          completed/         stats/        notes/
  BuyQueueScreen  CompletedBuysScreen BuyerStatsScreen ShiftNotesScreen
                                                           │
                                                           ▼
                                                       create/
                                                   TaskCreationScreen
```

## Detailed Route Definitions

### 1. Installation Route
- **Path**: `/install`
- **Name**: `install`
- **Screen**: `InstallationScreen`
- **Purpose**: First-time setup, API key configuration
- **Access**: Only when not authenticated

### 2. Dashboard Route
- **Path**: `/`
- **Name**: `dashboard`
- **Screen**: `DashboardScreen`
- **Purpose**: Main screen showing list of stores
- **Access**: Only when authenticated

### 3. Store Detail Route
- **Path**: `/store/:typeNum`
- **Name**: `store-detail`
- **Screen**: `StoreDetailScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Display detailed metrics and navigation for a specific store

### 4. Buy Queue Route
- **Path**: `/store/:typeNum/queue`
- **Name**: `store-queue`
- **Screen**: `BuyQueueScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Display current buy queue for the store

### 5. Completed Buys Route
- **Path**: `/store/:typeNum/completed`
- **Name**: `store-completed`
- **Screen**: `CompletedBuysScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Display completed buys for the store

### 6. Buyer Stats Route
- **Path**: `/store/:typeNum/stats`
- **Name**: `store-stats`
- **Screen**: `BuyerStatsScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Display buyer statistics and performance metrics

### 7. Shift Notes Route
- **Path**: `/store/:typeNum/notes`
- **Name**: `store-notes`
- **Screen**: `ShiftNotesScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Display shift notes and tasks for the store

### 8. Task Creation Route
- **Path**: `/store/:typeNum/notes/create`
- **Name**: `store-notes-create`
- **Screen**: `TaskCreationScreen`
- **Parameters**:
  - `typeNum` (path) - Store type number (required)
  - `storeName` (query) - Store name (optional)
- **Purpose**: Create new shift notes or tasks

## Navigation Methods

### Standard GoRouter Methods

```dart
// Navigate to a route
context.go('/');
context.go('/store/12345');
context.go('/store/12345/queue');

// Navigate using named routes
context.goNamed('dashboard');
context.goNamed(
  'store-detail',
  pathParameters: {'typeNum': '12345'},
  queryParameters: {'storeName': 'Main Store'},
);

// Navigate back
context.pop();

// Check if can pop
if (context.canPop()) {
  context.pop();
}
```

### Custom Helper Extensions

The router provides convenient extension methods on `BuildContext`:

```dart
// Navigate to dashboard
context.goToDashboard();

// Navigate to installation
context.goToInstallation();

// Navigate to store detail
context.goToStoreDetail('12345', storeName: 'Store Name');

// Navigate to buy queue
context.goToQueue('12345', storeName: 'Store Name');

// Navigate to completed buys
context.goToCompleted('12345', storeName: 'Store Name');

// Navigate to buyer stats
context.goToStats('12345', storeName: 'Store Name');

// Navigate to shift notes
context.goToNotes('12345', storeName: 'Store Name');

// Navigate to task creation
context.goToTaskCreation('12345', storeName: 'Store Name');
```

## Authentication & Redirects

### Current Implementation

The router includes redirect logic for authentication flow:

```dart
redirect: (BuildContext context, GoRouterState state) {
  const isInstalled = true; // Placeholder - replace with actual check

  final isGoingToInstall = state.matchedLocation == '/install';

  if (!isInstalled) {
    return isGoingToInstall ? null : '/install';
  } else {
    return isGoingToInstall ? '/' : null;
  }
}
```

### Implementation Steps

1. **Create Authentication Provider**
   ```dart
   final authStateProvider = StreamProvider<bool>((ref) {
     final authService = ref.watch(authServiceProvider);
     return authService.authStateStream;
   });
   ```

2. **Create Secure Storage Service**
   ```dart
   class SecureStorageService {
     final FlutterSecureStorage _storage = const FlutterSecureStorage();

     Future<bool> hasApiKey() async {
       final apiKey = await _storage.read(key: 'api_key');
       return apiKey != null && apiKey.isNotEmpty;
     }

     Future<void> saveApiKey(String apiKey) async {
       await _storage.write(key: 'api_key', value: apiKey);
     }

     Future<void> deleteApiKey() async {
       await _storage.delete(key: 'api_key');
     }
   }
   ```

3. **Update Router Redirect Logic**
   ```dart
   redirect: (BuildContext context, GoRouterState state) async {
     final secureStorage = ref.read(secureStorageProvider);
     final isInstalled = await secureStorage.hasApiKey();

     final isGoingToInstall = state.matchedLocation == '/install';

     if (!isInstalled) {
       return isGoingToInstall ? null : '/install';
     } else {
       return isGoingToInstall ? '/' : null;
     }
   }
   ```

## State Refresh on Auth Changes

The router automatically refreshes when auth state changes using `GoRouterRefreshStream`:

```dart
refreshListenable: GoRouterRefreshStream(
  authState.asData != null
      ? Stream.value(authState.value)
      : const Stream.empty(),
),
```

This ensures the router re-evaluates redirects when:
- User logs in (saves API key)
- User logs out (deletes API key)
- API key becomes invalid

## Theme Configuration

The app uses Material 3 with a custom theme defined in `lib/app.dart`:

```dart
ThemeData(
  useMaterial3: true,
  colorScheme: ColorScheme.fromSeed(
    seedColor: const Color(0xFF2196F3), // Blue
    brightness: Brightness.light,
  ),
  // Custom component themes...
)
```

## EasyLoading Configuration

Loading indicators are configured in `lib/app.dart`:

```dart
EasyLoading.instance
  ..displayDuration = const Duration(milliseconds: 2000)
  ..indicatorType = EasyLoadingIndicatorType.fadingCircle
  ..loadingStyle = EasyLoadingStyle.dark
  // ... other settings
```

Usage in screens:
```dart
// Show loading
EasyLoading.show(status: 'Loading...');

// Show success
EasyLoading.showSuccess('Success!');

// Show error
EasyLoading.showError('Error occurred');

// Dismiss
EasyLoading.dismiss();
```

## Next Steps

### 1. Replace Placeholder Screens

In `lib/router/app_router.dart`, replace placeholder screen classes with actual imports:

```dart
// Remove placeholder classes
// Add actual imports:
import 'package:buyer_kiosk_live/presentation/screens/installation/installation_screen.dart';
import 'package:buyer_kiosk_live/presentation/screens/dashboard/dashboard_screen.dart';
// ... other screen imports
```

### 2. Implement Authentication

- Create `SecureStorageService`
- Create authentication provider
- Update redirect logic with actual API key checks
- Implement login/logout functionality

### 3. Create Actual Screens

Create screen files in their respective directories:
- `lib/presentation/screens/installation/installation_screen.dart`
- `lib/presentation/screens/dashboard/dashboard_screen.dart`
- `lib/presentation/screens/store_detail/store_detail_screen.dart`
- `lib/presentation/screens/queue/buy_queue_screen.dart`
- `lib/presentation/screens/completed/completed_buys_screen.dart`
- `lib/presentation/screens/stats/buyer_stats_screen.dart`
- `lib/presentation/screens/shift_notes/shift_notes_screen.dart`
- `lib/presentation/screens/shift_notes/task_creation_screen.dart`

### 4. Testing

Write navigation tests:
```dart
testWidgets('Navigation test', (tester) async {
  await tester.pumpWidget(
    ProviderScope(
      child: BuyerKioskApp(),
    ),
  );

  // Test navigation flows
});
```

## Troubleshooting

### Issue: Routes not working
- Verify route paths match exactly
- Check that all required parameters are provided
- Ensure router provider is properly set up

### Issue: Redirects not triggering
- Check auth state provider implementation
- Verify GoRouterRefreshStream is properly configured
- Ensure redirect logic is correct

### Issue: Back button not working
- Use `context.pop()` instead of `Navigator.pop()`
- Verify navigation stack has routes to pop

## Resources

- [GoRouter Documentation](https://pub.dev/packages/go_router)
- [Riverpod Documentation](https://riverpod.dev)
- [Flutter Navigation & Routing](https://docs.flutter.dev/ui/navigation)
