# Frontend Setup Guide

## Quick Start

### 1. Install Dependencies

```bash
cd frontend
npm install
```

### 2. Configure Environment

Copy `.env.example` to `.env.local` and update if needed:

```bash
cp .env.example .env.local
```

Default configuration:
```
VITE_API_URL=http://localhost:8000
VITE_WS_URL=ws://localhost:8000/ws
```

### 3. Start Backend API

Make sure the backend is running first:

```bash
# From project root
wsl bash -c "source ~/miniconda3/etc/profile.d/conda.sh && conda activate invoice-py311 && python run_server.py"
```

Backend will be available at: http://localhost:8000

### 4. Start Frontend Dev Server

```bash
cd frontend
npm run dev
```

Frontend will be available at: http://localhost:3000

## Project Structure

```
frontend/
├── src/
│   ├── api/                    # API client layer
│   │   ├── client.ts          # Axios instance with interceptors
│   │   ├── types.ts           # API type definitions
│   │   └── endpoints/
│   │       ├── documents.ts   # Document API calls
│   │       ├── annotations.ts # Annotation API calls
│   │       └── training.ts    # Training API calls
│   │
│   ├── components/            # React components
│   │   └── Dashboard.tsx      # Updated with real API integration
│   │
│   ├── hooks/                 # Custom React Hooks
│   │   ├── useDocuments.ts
│   │   ├── useDocumentDetail.ts
│   │   ├── useAnnotations.ts
│   │   └── useTraining.ts
│   │
│   ├── styles/
│   │   └── index.css         # Tailwind CSS entry
│   │
│   ├── App.tsx
│   └── main.tsx              # App entry point with QueryClient
│
├── components/               # Legacy components (to be migrated)
│   ├── Badge.tsx
│   ├── Button.tsx
│   ├── Layout.tsx
│   ├── DocumentDetail.tsx
│   ├── Training.tsx
│   ├── Models.tsx
│   └── UploadModal.tsx
│
├── tailwind.config.js        # Tailwind configuration
├── postcss.config.js
├── vite.config.ts
├── package.json
└── index.html
```

## Key Technologies

- **React 19** - UI framework
- **TypeScript** - Type safety
- **Vite** - Build tool
- **Tailwind CSS** - Styling (Warm Graphite theme)
- **Axios** - HTTP client
- **@tanstack/react-query** - Server state management
- **lucide-react** - Icon library

## API Integration

### Authentication

The app stores admin token in localStorage:

```typescript
localStorage.setItem('admin_token', 'your-token')
```

All API requests automatically include the `X-Admin-Token` header.

### Available Hooks

#### useDocuments

```typescript
const {
  documents,
  total,
  isLoading,
  uploadDocument,
  deleteDocument,
  triggerAutoLabel,
} = useDocuments({ status: 'labeled', limit: 20 })
```

#### useDocumentDetail

```typescript
const { document, annotations, isLoading } = useDocumentDetail(documentId)
```

#### useAnnotations

```typescript
const {
  createAnnotation,
  updateAnnotation,
  deleteAnnotation,
  verifyAnnotation,
  overrideAnnotation,
} = useAnnotations(documentId)
```

#### useTraining

```typescript
const {
  models,
  isLoadingModels,
  startTraining,
  downloadModel,
} = useTraining()
```

## Features Implemented

### Phase 1 (Completed)
- ✅ API client with axios interceptors
- ✅ Type-safe API endpoints
- ✅ React Query for server state
- ✅ Custom hooks for all APIs
- ✅ Dashboard with real data
- ✅ Local Tailwind CSS
- ✅ Environment configuration
- ✅ CORS configured in backend

### Phase 2 (TODO)
- [ ] Update DocumentDetail to use useDocumentDetail
- [ ] Update Training page to use useTraining hooks
- [ ] Update Models page with real data
- [ ] Add UploadModal integration with API
- [ ] Add react-router for proper routing
- [ ] Add error boundary
- [ ] Add loading states
- [ ] Add toast notifications

### Phase 3 (TODO)
- [ ] Annotation canvas with real data
- [ ] Batch upload functionality
- [ ] Auto-label progress polling
- [ ] Training job monitoring
- [ ] Model download functionality
- [ ] Search and filtering
- [ ] Pagination

## Development Tips

### Hot Module Replacement

Vite supports HMR. Changes will reflect immediately without page reload.

### API Debugging

Check browser console for API requests:
- Network tab shows all requests/responses
- Axios interceptors log errors automatically

### Type Safety

TypeScript types in `src/api/types.ts` match backend Pydantic schemas.

To regenerate types from backend:
```bash
# TODO: Add type generation script
```

### Backend API Documentation

Visit http://localhost:8000/docs for interactive API documentation (Swagger UI).

## Troubleshooting

### CORS Errors

If you see CORS errors:
1. Check backend is running at http://localhost:8000
2. Verify CORS settings in `src/web/app.py`
3. Check `.env.local` has correct `VITE_API_URL`

### Module Not Found

If imports fail:
```bash
rm -rf node_modules package-lock.json
npm install
```

### Types Not Matching

If API responses don't match types:
1. Check backend version is up-to-date
2. Verify types in `src/api/types.ts`
3. Check API response in Network tab

## Next Steps

1. Run `npm install` to install dependencies
2. Start backend server
3. Run `npm run dev` to start frontend
4. Open http://localhost:3000
5. Create an admin token via backend API
6. Store token in localStorage via browser console:
   ```javascript
   localStorage.setItem('admin_token', 'your-token-here')
   ```
7. Refresh page to see authenticated API calls

## Production Build

```bash
npm run build
npm run preview  # Preview production build
```

Build output will be in `dist/` directory.
