# IGNY8 Frontend Documentation

**Version:** 1.0  
**Last Updated:** 2025-01-XX  
**Purpose:** Complete frontend documentation covering pages, components, templates, routing, state management, and configuration system.

---

## Table of Contents

1. [Frontend Overview](#frontend-overview)
2. [Tech Stack](#tech-stack)
3. [Project Structure](#project-structure)
4. [Routing System](#routing-system)
5. [Template System](#template-system)
6. [Component Library](#component-library)
7. [State Management](#state-management)
8. [API Integration](#api-integration)
9. [Configuration System](#configuration-system)
10. [Pages](#pages)
11. [Hooks](#hooks)
12. [Utilities](#utilities)

---

## Frontend Overview

The IGNY8 frontend is a React 19 application built with TypeScript, using Vite as the build tool and Tailwind CSS for styling. The frontend follows a configuration-driven architecture where UI components are rendered from configuration objects, eliminating code duplication and ensuring consistency.

### Key Features

- **Configuration-Driven UI**: All tables, filters, and forms driven by config files
- **4 Universal Templates**: DashboardTemplate, TablePageTemplate, FormPageTemplate, SystemPageTemplate
- **TypeScript**: Full type safety across the application
- **Zustand State Management**: Lightweight, performant state management
- **React Router v6**: Modern routing with nested routes
- **Responsive Design**: Mobile-first approach with Tailwind CSS

---

## Tech Stack

### Core Technologies

- **React 19**: UI library
- **TypeScript**: Type safety
- **Vite**: Build tool and dev server
- **Tailwind CSS**: Utility-first CSS framework
- **React Router v6**: Client-side routing

### State Management

- **Zustand**: Lightweight state management library
- **localStorage**: Persistence for Zustand stores

### HTTP Client

- **Fetch API**: Native browser API with custom wrapper
- **Auto-retry**: Automatic retry on network failures
- **Token refresh**: Automatic JWT token refresh

### UI Components

- **Custom Component Library**: Built-in components (Button, Card, Modal, etc.)
- **Icons**: Custom icon library
- **Toast Notifications**: Toast notification system

---

## Project Structure

```
frontend/src/
├── pages/                    # Page components
│   ├── Planner/              # Planner module pages
│   │   ├── Dashboard.tsx
│   │   ├── Keywords.tsx
│   │   ├── Clusters.tsx
│   │   └── Ideas.tsx
│   ├── Writer/               # Writer module pages
│   │   ├── Dashboard.tsx
│   │   ├── Tasks.tsx
│   │   ├── Content.tsx
│   │   ├── Drafts.tsx
│   │   ├── Images.tsx
│   │   └── Published.tsx
│   ├── Settings/             # Settings pages
│   │   ├── General.tsx
│   │   ├── Users.tsx
│   │   ├── Sites.tsx
│   │   ├── Integration.tsx
│   │   └── ...
│   ├── AuthPages/            # Authentication pages
│   │   ├── SignIn.tsx
│   │   └── SignUp.tsx
│   └── ...
├── templates/                # 4 universal templates
│   ├── DashboardTemplate.tsx
│   ├── TablePageTemplate.tsx
│   ├── FormPageTemplate.tsx
│   └── SystemPageTemplate.tsx
├── components/               # UI components
│   ├── layout/               # Layout components
│   │   ├── AppLayout.tsx
│   │   ├── Sidebar.tsx
│   │   └── Header.tsx
│   ├── table/                # Table components
│   │   ├── DataTable.tsx
│   │   ├── Filters.tsx
│   │   └── Pagination.tsx
│   ├── ui/                   # UI primitives
│   │   ├── button/
│   │   ├── card/
│   │   ├── modal/
│   │   └── ...
│   └── auth/                 # Auth components
│       └── ProtectedRoute.tsx
├── config/                   # Configuration files
│   ├── pages/                # Page-specific configs
│   │   └── keywords.config.tsx
│   ├── snippets/             # Shared snippets
│   │   ├── columns.snippets.ts
│   │   ├── filters.snippets.ts
│   │   └── actions.snippets.ts
│   └── routes.config.ts      # Route configuration
├── store/                    # Zustand stores
│   ├── authStore.ts          # Authentication state
│   ├── plannerStore.ts       # Planner module state
│   ├── siteStore.ts          # Site selection state
│   ├── sectorStore.ts        # Sector selection state
│   ├── aiRequestLogsStore.ts # AI request/response logs
│   └── pageSizeStore.ts      # Table page size preference
├── services/                 # API clients
│   └── api.ts                # fetchAPI, API functions
├── hooks/                    # Custom React hooks
│   ├── useProgressModal.ts   # Progress modal for long-running tasks
│   └── useAuth.ts            # Authentication hook
├── layout/                   # Layout components
│   └── AppLayout.tsx         # Main app layout wrapper
├── utils/                    # Utility functions
│   └── difficulty.ts         # Difficulty utilities
├── App.tsx                   # Root component with routing
└── main.tsx                  # Entry point
```

---

## Routing System

### Route Structure

**File**: `App.tsx`

**Public Routes**:
- `/signin` - Sign in page
- `/signup` - Sign up page

**Protected Routes** (require authentication):
- `/` - Home/Dashboard
- `/planner` - Planner Dashboard
- `/planner/keywords` - Keywords page
- `/planner/clusters` - Clusters page
- `/planner/ideas` - Ideas page
- `/writer` - Writer Dashboard
- `/writer/tasks` - Tasks page
- `/writer/content` - Content page
- `/writer/drafts` - Drafts page
- `/writer/images` - Images page
- `/writer/published` - Published page
- `/thinker` - Thinker Dashboard
- `/thinker/prompts` - Prompts page
- `/thinker/author-profiles` - Author Profiles page
- `/thinker/strategies` - Strategies page
- `/thinker/image-testing` - Image Testing page
- `/billing/credits` - Credits page
- `/billing/transactions` - Transactions page
- `/billing/usage` - Usage page
- `/settings` - Settings pages
- `/analytics` - Analytics page
- `/schedules` - Schedules page

### Route Configuration

**File**: `config/routes.config.ts`

Defines route metadata including:
- Route paths
- Labels for navigation
- Icons
- Breadcrumb labels
- Nested route structure

### Protected Routes

**Component**: `components/auth/ProtectedRoute.tsx`

**Functionality**:
- Checks authentication status from `authStore`
- Redirects to `/signin` if not authenticated
- Wraps protected routes with `AppLayout`

---

## Template System

### 1. DashboardTemplate

**Purpose**: Module home pages with KPIs, workflow steps, and charts.

**Usage**:
```tsx
<DashboardTemplate
  title="Planner Dashboard"
  subtitle="Manage your SEO keywords and content planning"
  metrics={metrics}
  workflowSteps={steps}
  charts={charts}
/>
```

**Features**:
- Header metrics (KPIs)
- Workflow steps
- Charts and visualizations
- Quick actions

### 2. TablePageTemplate

**Purpose**: CRUD table pages (Keywords, Clusters, Tasks, etc.).

**Usage**:
```tsx
<TablePageTemplate
  title="Keywords"
  subtitle="Manage and organize SEO keywords"
  columns={columns}
  data={data}
  filters={filterConfig}
  onSort={(field, direction) => ...}
  onEdit={(row) => ...}
  onDelete={(row) => ...}
  bulkActions={bulkActions}
/>
```

**Features**:
- Data table with sorting
- Filters (text, select, date range, custom)
- Pagination
- Bulk actions
- Row actions (edit, delete)
- AI Request/Response Logs section
- Import/Export functionality

**Configuration**:
- `columns`: Column definitions (key, label, sortable, render, etc.)
- `filters`: Filter definitions (type, options, custom render)
- `bulkActions`: Bulk action definitions
- `actions`: Row action definitions

### 3. FormPageTemplate

**Purpose**: Settings/form pages (Settings, Integration, etc.).

**Usage**:
```tsx
<FormPageTemplate
  title="Settings"
  subtitle="Configure your account settings"
  sections={sections}
  onSubmit={(data) => ...}
/>
```

**Features**:
- Form sections
- Form validation
- Save/Cancel buttons
- Success/Error notifications

### 4. SystemPageTemplate

**Purpose**: System/admin pages (Logs, Status, Monitoring).

**Usage**:
```tsx
<SystemPageTemplate
  title="System Status"
  subtitle="Monitor system health and performance"
  content={content}
/>
```

**Features**:
- System information display
- Logs viewer
- Status indicators
- Performance metrics

---

## Component Library

### Layout Components

#### AppLayout
**File**: `layout/AppLayout.tsx`

**Purpose**: Main app layout wrapper.

**Features**:
- Sidebar navigation
- Header with user menu
- Main content area
- Breadcrumbs

#### Sidebar
**File**: `components/layout/Sidebar.tsx`

**Purpose**: Navigation sidebar.

**Features**:
- Module navigation
- Active route highlighting
- Collapsible sections

#### Header
**File**: `components/layout/Header.tsx`

**Purpose**: Top header bar.

**Features**:
- User menu
- Notifications
- Site/Sector selector

### Table Components

#### DataTable
**File**: `components/table/DataTable.tsx`

**Purpose**: Data table component.

**Features**:
- Sortable columns
- Selectable rows
- Row actions
- Responsive design

#### Filters
**File**: `components/table/Filters.tsx`

**Purpose**: Filter component.

**Features**:
- Text filters
- Select filters
- Date range filters
- Custom filters

#### Pagination
**File**: `components/ui/pagination/CompactPagination.tsx`

**Purpose**: Pagination component.

**Features**:
- Page navigation
- Page size selector
- Total count display

### UI Components

#### Button
**File**: `components/ui/button/Button.tsx`

**Variants**: primary, secondary, danger, ghost, link

**Sizes**: sm, md, lg

#### Card
**File**: `components/ui/card/Card.tsx`

**Purpose**: Card container component.

#### Modal
**File**: `components/ui/modal/Modal.tsx`

**Purpose**: Modal dialog component.

**Variants**: FormModal, ProgressModal, AlertModal

#### Toast
**File**: `components/ui/toast/ToastContainer.tsx`

**Purpose**: Toast notification system.

**Types**: success, error, warning, info

#### Input
**File**: `components/form/input/InputField.tsx`

**Purpose**: Text input component.

#### Select
**File**: `components/form/SelectDropdown.tsx`

**Purpose**: Select dropdown component.

#### Checkbox
**File**: `components/form/input/Checkbox.tsx`

**Purpose**: Checkbox component.

### Auth Components

#### ProtectedRoute
**File**: `components/auth/ProtectedRoute.tsx`

**Purpose**: Route protection component.

**Functionality**:
- Checks authentication
- Redirects to signin if not authenticated
- Wraps children with AppLayout

---

## State Management

### Zustand Stores

#### authStore
**File**: `store/authStore.ts`

**State**:
- `user`: Current user object
- `token`: JWT access token
- `refreshToken`: JWT refresh token
- `isAuthenticated`: Authentication status
- `loading`: Loading state

**Actions**:
- `login(email, password)`: Sign in user
- `logout()`: Sign out user
- `register(data)`: Register new user
- `setUser(user)`: Set user object
- `setToken(token)`: Set access token
- `refreshToken()`: Refresh access token

**Persistence**: localStorage (persisted)

#### plannerStore
**File**: `store/plannerStore.ts`

**State**: Planner module-specific state

**Actions**: Planner module actions

#### siteStore
**File**: `store/siteStore.ts`

**State**:
- `activeSite`: Currently selected site
- `sites`: List of accessible sites

**Actions**:
- `setActiveSite(site)`: Set active site
- `loadSites()`: Load accessible sites

**Persistence**: localStorage (persisted)

#### sectorStore
**File**: `store/sectorStore.ts`

**State**:
- `activeSector`: Currently selected sector
- `sectors`: List of sectors for active site

**Actions**:
- `setActiveSector(sector)`: Set active sector
- `loadSectorsForSite(siteId)`: Load sectors for site

**Persistence**: localStorage (persisted)

#### aiRequestLogsStore
**File**: `store/aiRequestLogsStore.ts`

**State**:
- `logs`: Array of AI request/response logs

**Actions**:
- `addLog(log)`: Add new log entry
- `addRequestStep(logId, step)`: Add request step to log
- `addResponseStep(logId, step)`: Add response step to log
- `updateLog(logId, data)`: Update log entry
- `clearLogs()`: Clear all logs

**Purpose**: Tracks AI function execution with step-by-step logs

#### pageSizeStore
**File**: `store/pageSizeStore.ts`

**State**:
- `pageSize`: Table page size preference

**Actions**:
- `setPageSize(size)`: Set page size

**Persistence**: localStorage (persisted)

---

## API Integration

### API Service

**File**: `services/api.ts`

**Functions**:
- `fetchAPI(url, options)`: Generic API fetch wrapper
- `fetchKeywords(filters)`: Fetch keywords
- `createKeyword(data)`: Create keyword
- `updateKeyword(id, data)`: Update keyword
- `deleteKeyword(id)`: Delete keyword
- `bulkDeleteKeywords(ids)`: Bulk delete keywords
- `autoClusterKeywords(ids)`: Auto-cluster keywords
- `fetchClusters(filters)`: Fetch clusters
- `autoGenerateIdeas(clusterIds)`: Auto-generate ideas
- `fetchTasks(filters)`: Fetch tasks
- `autoGenerateContent(taskIds)`: Auto-generate content
- `autoGenerateImages(taskIds)`: Auto-generate images
- And more...

**Features**:
- Automatic JWT token inclusion
- Automatic token refresh on 401
- Auto-retry on network failures
- Error handling
- Request/response logging

### API Base URL

**Auto-detection**:
- Checks environment variables (`VITE_BACKEND_URL`, `VITE_API_URL`)
- Falls back to auto-detection based on current origin
- Supports localhost, IP addresses, and production subdomain

**Default**: `https://api.igny8.com/api`

---

## Configuration System

### Page-Local Config

**Location**: `config/pages/`

**Example**: `keywords.config.tsx`

**Structure**:
```tsx
export const createKeywordsPageConfig = () => ({
  columns: [...],
  filters: [...],
  bulkActions: [...],
  actions: [...],
});
```

**Usage**:
```tsx
import { createKeywordsPageConfig } from '../../config/pages/keywords.config';

const config = createKeywordsPageConfig();
```

### Shared Snippets

**Location**: `config/snippets/`

#### columns.snippets.ts
**Purpose**: Reusable column definitions.

**Examples**:
- `statusColumn`: Status column with badge
- `titleColumn`: Title column with link
- `dateColumn`: Date column with formatting

#### filters.snippets.ts
**Purpose**: Reusable filter definitions.

**Examples**:
- `statusFilter`: Status dropdown filter
- `dateRangeFilter`: Date range filter
- `searchFilter`: Text search filter

#### actions.snippets.ts
**Purpose**: Reusable action definitions.

**Examples**:
- `commonActions`: Edit, Delete actions
- `bulkActions`: Bulk delete, bulk update actions

### Route Configuration

**File**: `config/routes.config.ts`

**Structure**:
```tsx
export const routes: RouteConfig[] = [
  {
    path: '/planner',
    label: 'Planner',
    icon: 'Planner',
    children: [
      { path: '/planner/keywords', label: 'Keywords' },
      ...
    ],
  },
  ...
];
```

**Functions**:
- `getBreadcrumbs(pathname)`: Get breadcrumbs for current route

---

## Pages

### Planner Module

#### Keywords Page
**File**: `pages/Planner/Keywords.tsx`

**Features**:
- Keyword CRUD operations
- Auto-cluster functionality
- Import/Export (CSV)
- Filters (status, cluster, intent, difficulty, volume)
- Bulk actions (delete, status update)
- AI Request/Response Logs

**Configuration**: Uses `keywords.config.tsx`

#### Clusters Page
**File**: `pages/Planner/Clusters.tsx`

**Features**:
- Cluster CRUD operations
- Auto-generate ideas functionality
- Filters (status, sector)
- Bulk actions

#### Ideas Page
**File**: `pages/Planner/Ideas.tsx`

**Features**:
- Content ideas CRUD operations
- Filters (status, cluster, content type)
- Bulk actions

### Writer Module

#### Tasks Page
**File**: `pages/Writer/Tasks.tsx`

**Features**:
- Task CRUD operations
- Auto-generate content functionality
- Auto-generate images functionality
- Filters (status, cluster, content type)
- Bulk actions

### Settings Pages

#### Sites Page
**File**: `pages/Settings/Sites.tsx`

**Features**:
- Site CRUD operations
- Site activation/deactivation
- Multiple sites can be active simultaneously

#### Integration Page
**File**: `pages/Settings/Integration.tsx`

**Features**:
- Integration settings (OpenAI, Runware)
- API key configuration
- Test connections
- Image generation testing

---

## Hooks

### useProgressModal

**File**: `hooks/useProgressModal.ts`

**Purpose**: Progress modal for long-running Celery tasks.

**Usage**:
```tsx
const progressModal = useProgressModal();

// Start task
progressModal.start(taskId, 'Task started...');

// Task progress is automatically polled
// Modal displays progress updates
```

**Features**:
- Automatic polling of task progress
- Progress percentage display
- Step-by-step logs (request/response steps)
- Success/Error handling
- Auto-close on completion

### useAuth

**File**: `hooks/useAuth.ts`

**Purpose**: Authentication hook.

**Usage**:
```tsx
const { user, isAuthenticated, login, logout } = useAuth();
```

**Features**:
- Access to auth state
- Login/logout functions
- Authentication status

---

## Utilities

### Difficulty Utilities

**File**: `utils/difficulty.ts`

**Functions**:
- `getDifficultyLabelFromNumber(number)`: Get difficulty label (Easy, Medium, Hard)
- `getDifficultyRange()`: Get difficulty range options

### API Utilities

**File**: `services/api.ts`

**Helper Functions**:
- `getActiveSiteId()`: Get active site ID from store
- `getActiveSectorId()`: Get active sector ID from store
- `getAuthToken()`: Get JWT token from store
- `getRefreshToken()`: Get refresh token from store

---

## Summary

The IGNY8 frontend is built on:

1. **Configuration-Driven Architecture**: Zero duplication, single source of truth
2. **4 Universal Templates**: Reusable templates for all page types
3. **TypeScript**: Full type safety
4. **Zustand State Management**: Lightweight, performant state management
5. **React Router v6**: Modern routing with nested routes
6. **Component Library**: Reusable UI components
7. **API Integration**: Automatic token handling and error management
8. **Responsive Design**: Mobile-first with Tailwind CSS

This architecture ensures consistency, maintainability, and extensibility while providing a great user experience.

