# Mock Interface Standards

## Mock Interface Checklist

- [ ] Mock banner on directory and flow index pages only ([Mock Banner](#mock-banner-requirement))
- [ ] All user flows are complete and navigable ([User Flow Design](#user-flow-design))
- [ ] Mock data represents realistic scenarios ([Mock Data Guidelines](#mock-data-guidelines))
- [ ] Loading states simulate realistic timing ([State Simulation](#state-simulation))
- [ ] Error states are handled gracefully ([State Simulation](#state-simulation))
- [ ] Success confirmations provide clear feedback ([State Simulation](#state-simulation))
- [ ] Interface is fully responsive ([Responsive Design](#responsive-design))
- [ ] Reset/restart functionality available ([User Controls](#user-controls))
- [ ] Documentation includes stakeholder instructions ([Documentation Requirements](#documentation-requirements))
- [ ] Mock services are integration-ready ([Integration Readiness](#integration-readiness))
- [ ] No production dependencies exist ([Isolation Principle](#isolation-principle))

## Purpose and Philosophy

Mock interfaces serve as interactive prototypes for stakeholder review, user testing, and design validation before backend implementation. They bridge the gap between static designs and working software, allowing teams to validate user experience, gather feedback, and iterate quickly without backend dependencies.

**Why:** Early validation saves development time, ensures alignment with stakeholder expectations, and allows UX testing before committing to backend implementation. Mock interfaces also serve as living specifications for developers.

## Directory Structure

### Organization Pattern
Mock interfaces live in a dedicated directory structure separate from production code.

```
src/app/mock/
├── page.tsx                          # Mock directory listing all flows
├── [flow-name]/                      # Individual mock flow
│   ├── page.tsx                      # Flow dashboard/landing
│   ├── [step-name]/                  # Individual steps in flow
│   │   └── page.tsx                  # Step implementation
│   ├── components/                   # Flow-specific components
│   │   ├── MockBanner.tsx           # Mock indicator (flow index only)
│   │   └── StepComponents.tsx       # Step-specific components
│   ├── services/                     # Mock data services
│   │   └── mockDataService.ts       # Simulated API responses
│   ├── assets/                       # Mock assets (images, videos, etc.)
│   │   └── books/                    # Organized by entity
│   │       └── [book-slug]/          # All assets for one book
│   ├── types.ts                      # TypeScript interfaces
│   └── README.md                     # Flow documentation
```

### Example Implementation
```typescript
// src/app/mock/page.tsx - Main directory
export default function MockDirectory() {
  const mockFlows = [
    {
      id: 'book-to-video',
      title: 'Book to Video Generation',
      status: 'active',
      path: '/mock/book-to-video'
    },
    {
      id: 'author-onboarding',
      title: 'Author Onboarding',
      status: 'planned',
      path: '/mock/author-onboarding'
    }
  ];

  return (
    <div className="mock-directory">
      <MockBanner />
      <h1>Mock Interface Directory</h1>
      {/* Flow cards with status indicators */}
    </div>
  );
}
```

## Asset Management for Mock Interfaces

Mock interfaces should keep all assets within the mock directory structure, organized by the entities they belong to.

**Why:** Keeping mock assets within the mock directory ensures they don't pollute production builds, makes cleanup straightforward, and maintains clear separation between prototype and production resources. Organizing by entity (e.g., by book) keeps all related assets together.

### Asset Organization Structure

```typescript
src/app/mock/[flow-name]/
├── assets/                          # All mock assets in one place
│   └── books/                       # Organized by book
│       ├── pride-prejudice/         # All assets for one book
│       │   ├── starting-images/     # Starting images for video segments
│       │   │   ├── opening-scene.jpg
│       │   │   ├── character-intro.jpg
│       │   │   └── climax-scene.jpg
│       │   ├── cover.jpg            # Book cover
│       │   ├── thumbnails/          # Video thumbnails
│       │   │   └── main-thumbnail.jpg
│       │   └── videos/              # Generated videos for this book
│       │       ├── atmospheric-trailer.mp4
│       │       ├── author-interview.mp4
│       │       └── cinematic-teaser.mp4
│       └── [other-books]/
```

### Asset Organization Principles

- **Entity-based:** Group all assets by the primary entity (book, author, etc.)
- **Purpose-driven subfolders:** Separate by usage (starting-images, videos, thumbnails)
- **Self-contained:** Each book has everything needed for its demos

### Asset Serving Strategy

Mock assets should be served through Next.js API routes to maintain control and security:

```typescript
// API route: app/api/mock/assets/[...path]/route.ts
export async function GET(request, { params }) {
  const filePath = params.path.join('/');
  // Security checks and file serving logic
  return new NextResponse(fileBuffer, {
    headers: { 'Content-Type': contentType }
  });
}

// Usage in mock service
const startingImage = `/api/mock/assets/books/${bookSlug}/starting-images/${imageName}`;
const videoUrl = `/api/mock/assets/books/${bookSlug}/videos/${videoName}`;
const thumbnailUrl = `/api/mock/assets/books/${bookSlug}/thumbnails/${thumbName}`;
```

### Asset Requirements

- **Starting Images:** 800x450px (16:9), under 500KB, for video segment starting points
- **Book Covers:** 400x600px (2:3), under 300KB  
- **Video Thumbnails:** 1280x720px (16:9), under 500KB
- **Videos:** MP4 format, H.264 codec, under 50MB for mock demos
- **Naming:** Descriptive names (e.g., `opening-ballroom.jpg`, not `img1.jpg`)

## Core Design Principles

### Mock Banner Requirement
Mock banners should appear ONLY on the main mock directory (`/mock`) and flow index pages (`/mock/[flow-name]`), NOT on individual step pages. This reduces visual clutter while still making the prototype status clear at entry points.

```typescript
// components/MockBanner.tsx - Use only on directory and flow index
export const MockBanner = () => (
  <div className="bg-yellow-50 border-b border-yellow-200 px-4 py-2 text-center">
    <p className="text-sm text-yellow-800 font-medium">
      ⚠️ MOCK INTERFACE - Not Connected to Backend
    </p>
  </div>
);

// On /mock/page.tsx and /mock/book-to-video/page.tsx
<MockBanner />

// NOT on /mock/book-to-video/upload/page.tsx (individual steps)
```

### User Flow Design
Design complete, realistic user journeys from start to finish.

```typescript
// Flow with clear progression
const flowSteps = [
  { id: 'upload', title: 'Upload File', status: 'completed' },
  { id: 'process', title: 'Process Content', status: 'current' },
  { id: 'review', title: 'Review Results', status: 'pending' },
  { id: 'download', title: 'Download Output', status: 'pending' }
];
```

### State Simulation
Simulate all states users might encounter.

```typescript
// Realistic state progression
const simulateProcessing = () => {
  setStatus('uploading');
  
  setTimeout(() => {
    setStatus('processing');
    setProgress(25);
  }, 1000);
  
  setTimeout(() => {
    setProgress(75);
  }, 2500);
  
  setTimeout(() => {
    setStatus('complete');
    setProgress(100);
  }, 4000);
};
```

## Mock Data Guidelines

### Realistic Data
Use data that represents real-world scenarios.

```typescript
// Mock data service
export class MockDataService {
  // Use realistic data, not Lorem Ipsum
  private mockBooks = [
    {
      id: 'book_001',
      title: 'The Midnight Garden',
      author: 'Sarah Mitchell',
      genre: 'Contemporary Fiction',
      pageCount: 342,
      language: 'English',
      publicationYear: 2023
    }
  ];

  // Simulate API delays
  async getBook(id: string): Promise<Book> {
    await this.simulateDelay(800);
    return this.mockBooks.find(book => book.id === id);
  }

  private simulateDelay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
```

### Asset Data Strategy

When mock interfaces need images or media:

```typescript
class MockAssetsService {
  private getBookAsset(
    bookSlug: string, 
    assetType: 'starting-images' | 'videos' | 'thumbnails', 
    fileName: string
  ): string {
    // Check if local assets exist for this book
    const booksWithAssets = ['pride-prejudice', 'midnight-garden'];
    
    if (booksWithAssets.includes(bookSlug)) {
      // Use local mock assets
      return `/api/mock/assets/books/${bookSlug}/${assetType}/${fileName}`;
    }
    
    // Fallback to external placeholders for quick prototyping
    if (assetType === 'starting-images' || assetType === 'thumbnails') {
      return `https://picsum.photos/seed/${bookSlug}_${fileName}/800/450`;
    }
    
    // Return a default video URL for books without mock videos
    return '/api/mock/assets/default-video.mp4';
  }
}
```

**Why:** This approach keeps all book-related assets together, making it easy to add new books or update existing ones without scattered files.

### Data Consistency
Maintain data consistency across the mock flow.

```typescript
// Use context or state management for flow data
const MockFlowContext = createContext<{
  uploadedFile: File | null;
  analysisResults: AnalysisResult | null;
  selectedOptions: UserSelections | null;
}>({
  uploadedFile: null,
  analysisResults: null,
  selectedOptions: null
});
```

## User Controls

### Reset Functionality
Provide ways to reset and restart the demo.

```typescript
const ResetButton = () => {
  const resetFlow = () => {
    // Clear all state
    localStorage.removeItem('mockFlowState');
    // Reset to initial step
    router.push('/mock/flow-name');
    // Show confirmation
    toast.success('Demo reset successfully');
  };

  return (
    <button onClick={resetFlow} className="reset-button">
      Reset Demo
    </button>
  );
};
```

### Navigation Controls
Enable free navigation between steps for review.

```typescript
const StepNavigation = ({ currentStep, totalSteps }) => {
  return (
    <div className="step-navigation">
      <button 
        onClick={() => navigateToStep(currentStep - 1)}
        disabled={currentStep === 0}
      >
        Previous
      </button>
      <span>{currentStep + 1} / {totalSteps}</span>
      <button 
        onClick={() => navigateToStep(currentStep + 1)}
        disabled={currentStep === totalSteps - 1}
      >
        Next
      </button>
    </div>
  );
};
```

## Responsive Design

### Mobile-First Approach
Design for mobile screens first, then enhance for larger screens.

```typescript
// Responsive mock interface
<div className="px-4 sm:px-6 lg:px-8">
  <h1 className="text-2xl sm:text-3xl lg:text-4xl">
    Mock Interface Title
  </h1>
  
  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
    {/* Responsive grid layout */}
  </div>
</div>
```

## Basic Accessibility (Optional)

While comprehensive accessibility is not required for mock interfaces (they're temporary prototypes), basic usability should be maintained through standard HTML semantics and responsive design. Focus on making the interface usable for stakeholder demos rather than full WCAG compliance.

## Integration Readiness

### Service Abstraction
Structure mock services for easy replacement with real APIs.

```typescript
// Interface matching future API
interface IBookService {
  uploadBook(file: File): Promise<UploadResult>;
  analyzeBook(bookId: string): Promise<AnalysisResult>;
  generateVideo(options: VideoOptions): Promise<VideoResult>;
}

// Mock implementation
export class MockBookService implements IBookService {
  async uploadBook(file: File): Promise<UploadResult> {
    // Mock implementation
  }
}

// Future: Replace with real implementation
export class BookService implements IBookService {
  async uploadBook(file: File): Promise<UploadResult> {
    // Real API call
  }
}
```

### Configuration Pattern
Use environment-based configuration for easy switching.

```typescript
// config/services.ts
const createServices = () => {
  if (process.env.USE_MOCK_SERVICES === 'true') {
    return {
      bookService: new MockBookService(),
      videoService: new MockVideoService()
    };
  }
  
  return {
    bookService: new BookService(API_URL),
    videoService: new VideoService(API_URL)
  };
};
```

## Isolation Principle

### No Production Dependencies
Mock interfaces must not import or depend on production code.

```typescript
// ❌ WRONG - Don't import production services
import { BookService } from '@/services/book.service';

// ✅ CORRECT - Use mock services
import { MockBookService } from './services/mockBookService';
```

### Separate Routing
Keep mock routes clearly separated from production routes.

```typescript
// app/mock/* - All mock interfaces
// app/* - Production routes

// Middleware to prevent mock access in production
export function middleware(request: NextRequest) {
  if (
    request.nextUrl.pathname.startsWith('/mock') &&
    process.env.NODE_ENV === 'production' &&
    !process.env.ENABLE_MOCKS
  ) {
    return NextResponse.redirect(new URL('/', request.url));
  }
}
```

## Documentation Requirements

### Flow Documentation
Each mock flow must have a README explaining its purpose and usage.

```markdown
# Mock Interface: [Flow Name]

## Overview
Brief description of what this mock interface demonstrates.

## Access URL
- Development: http://localhost:3000/mock/flow-name
- Staging: https://staging.example.com/mock/flow-name

## User Flow
1. Step 1: User uploads a file
2. Step 2: System processes the file
3. Step 3: User reviews results
4. Step 4: User downloads output

## Mock Data
Describes the mock data used and any limitations.

## Testing Instructions
1. How to test the happy path
2. How to trigger error states
3. How to reset the demo

## Integration Notes
- API endpoints this will connect to
- Data structures that need to match
- Services that will replace mocks
```

### Inline Documentation
Document complex mock logic for future developers.

```typescript
/**
 * Simulates the book analysis process with realistic delays
 * and progress updates to match expected backend behavior.
 * 
 * Timing:
 * - Upload: 1-2 seconds
 * - Text extraction: 3-5 seconds  
 * - AI analysis: 5-8 seconds
 * - Total: ~15 seconds
 */
const simulateBookAnalysis = async (file: File) => {
  // Implementation
};
```

## Testing Mock Interfaces

### Manual Testing Guidelines
For stakeholder reviews, provide clear instructions in the README about what to test:
- Happy path flow from start to finish
- Different selection options
- Mobile responsiveness
- Error recovery (if implemented)
- Loading states and transitions

Testing checklists can be included in documentation rather than as interactive components.

## Performance Considerations

### Optimize Mock Assets
Keep mock interfaces lightweight for quick loading.

```typescript
// Use optimized placeholder images
const PlaceholderImage = ({ width, height, text }) => {
  return (
    <div 
      className="placeholder-image"
      style={{ width, height }}
      aria-label={text}
    >
      <span>{text}</span>
    </div>
  );
};

// Lazy load heavy components
const HeavyComponent = lazy(() => import('./HeavyComponent'));
```

## Common Patterns

### Progress Tracking Pattern
```typescript
const ProgressTracker = ({ steps, currentStep }) => {
  return (
    <div className="progress-tracker">
      {steps.map((step, index) => (
        <div 
          key={step.id}
          className={cn('step', {
            'completed': index < currentStep,
            'current': index === currentStep,
            'pending': index > currentStep
          })}
        >
          <span className="step-number">{index + 1}</span>
          <span className="step-title">{step.title}</span>
        </div>
      ))}
    </div>
  );
};
```

### Mock Delay Pattern
```typescript
const useMockDelay = (minMs: number, maxMs: number) => {
  const delay = useCallback(() => {
    const ms = Math.random() * (maxMs - minMs) + minMs;
    return new Promise(resolve => setTimeout(resolve, ms));
  }, [minMs, maxMs]);
  
  return delay;
};
```

### State Persistence Pattern
```typescript
const useMockPersistence = (key: string, initialValue: any) => {
  const [value, setValue] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem(key);
      return saved ? JSON.parse(saved) : initialValue;
    }
    return initialValue;
  });
  
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  
  return [value, setValue];
};
```

## Migration to Production

### Checklist for Production Migration
Steps to convert mock interface to production:

1. Replace mock services with real API clients
2. Remove mock banner component
3. Update routing from /mock/* to production routes
4. Replace mock delays with actual API calls
5. Update error handling for real API errors
6. Remove reset/demo controls
7. Add proper authentication/authorization
8. Update documentation
9. Remove from mock directory listing
10. Archive mock code for reference

### Asset Migration Checklist

When migrating mock interfaces to production:

1. Review which mock assets to keep for production
2. Move selected book assets to production storage:
   - Starting images → Cloud storage/CDN
   - Videos → Video streaming service  
   - Thumbnails → CDN
3. Update asset URLs from `/api/mock/assets/` to production URLs
4. Remove mock asset API route
5. Delete entire `assets/` folder from mock directory
6. Update services to use production asset management

Example migration:
```typescript
// Mock version
const startingImage = `/api/mock/assets/books/${bookSlug}/starting-images/opening.jpg`;
const videoUrl = `/api/mock/assets/books/${bookSlug}/videos/trailer.mp4`;

// Production version  
const startingImage = `${CDN_URL}/books/${bookSlug}/images/opening.jpg`;
const videoUrl = `${VIDEO_STREAMING_URL}/books/${bookSlug}/trailer.mp4`;
```

### Code Migration Example
```typescript
// Before (Mock)
const MockVideoGeneration = () => {
  const { generateMockVideo } = useMockVideoService();
  
  const handleGenerate = async () => {
    const result = await generateMockVideo(options);
    // Mock handling
  };
};

// After (Production)
const VideoGeneration = () => {
  const { generateVideo } = useVideoService();
  
  const handleGenerate = async () => {
    try {
      const result = await generateVideo(options);
      // Real handling
    } catch (error) {
      // Real error handling
    }
  };
};
```

## Anti-Patterns to Avoid

### ❌ Don't Mix Mock and Production Code
```typescript
// Wrong
const service = isDevelopment ? new MockService() : new RealService();
```

### ❌ Don't Use Lorem Ipsum
```typescript
// Wrong
const mockText = "Lorem ipsum dolor sit amet...";

// Right
const mockText = "Transform your manuscript into a compelling video";
```

### ❌ Don't Skip Error States
```typescript
// Wrong - Only happy path
const handleSubmit = () => {
  setStatus('success');
};

// Right - Include error scenarios
const handleSubmit = () => {
  if (Math.random() > 0.8) {
    setStatus('error');
    setErrorMessage('Network error - please try again');
  } else {
    setStatus('success');
  }
};
```

### ❌ Don't Forget Mobile Users
```typescript
// Wrong - Desktop only
<div style={{ width: '1200px' }}>

// Right - Responsive
<div className="w-full max-w-7xl mx-auto px-4">
```

This completes the mock interface standards, providing comprehensive guidelines for creating effective stakeholder review interfaces that are maintainable, realistic, and ready for production migration.