# Writer Frontend Module

**Location:** `frontend/src/pages/writer/`  
**Purpose:** UI components and pages for writer module

## Source Files

 # Writer Main Page (Queue/Drafts/Images Navigation)
 
 ## Purpose
 Serve as the entry surface for writer workflows, routing users to task queue, drafts, images, review, and published content views. It relies on shared table templates and writer navigation tabs defined in the content/tasks/images pages.
 
 ## Code Locations (exact paths)
 - Key pages under Writer:
   - Tasks (queue): `frontend/src/pages/Writer/Tasks.tsx`
   - Content drafts/list: `frontend/src/pages/Writer/Content.tsx`
   - Images: `frontend/src/pages/Writer/Images.tsx`
   - Content view: `frontend/src/pages/Writer/ContentView.tsx`
 - Navigation tabs defined inside Tasks/Content/Images pages (`writerTabs`).
 
 ## High-Level Responsibilities
 - Present writer-specific navigation and headers.
 - Delegate to module pages that implement task creation, AI generation, content listing, and image management.
 
 ## Detailed Behavior
 - Writer pages use shared navigation tabs (`writerTabs`: Queue, Drafts, Images, Review, Published) rendered via `ModuleNavigationTabs`.
 - Each page sets a header (`PageHeader`) with badge icon and binds to the tab component for consistent navigation.
 - State (filters, pagination, selections) is managed within each page; there is no global writer-state container beyond shared stores (`useSectorStore`, `usePageSizeStore`).
 
 ## Data Structures / Models Involved (no code)
 - Task, Content, ContentImage DTOs from `frontend/src/services/api` (writer endpoints).
 
 ## Execution Flow
 - User enters writer area via route (e.g., `/writer/tasks` or `/writer/content`).
 - Navigation tabs switch routes; each route mounts its page and fetches data (tasks/content/images).
 
 ## Cross-Module Interactions
 - Sector/site scoping via `useSectorStore` and backend query params in API calls.
 - Optimization and image generation actions route into optimizer or image generation APIs.
 
 ## State Transitions
 - Per-page loading/filters; navigation changes unmount current page and mount target page.
 
 ## Error Handling
 - Each page uses toasts for API errors; no shared error surface beyond per-page banners.
 
 ## Tenancy Rules
 - Backend filters by account/site/sector; pages pass sector context via filters or rely on server defaults.
 
 ## Billing Rules (if applicable)
 - None on navigation; individual actions (AI generation) consume credits on backend.
 
 ## Background Tasks / Schedulers (if applicable)
 - None at the navigation level.
 
 ## Key Design Considerations
 - Tabs keep writer UX consistent; each page owns its data loading to avoid cross-coupling.
 
 ## How Developers Should Work With This Module
 - When adding a new writer view (e.g., “Outlines”), add a tab entry and a route in `App.tsx`, and implement the page with the same header/tab pattern.
 # Image Editor Page (Images List & Generation)
 
 ## Purpose
 Manage generated images linked to writer content: list images grouped by content, filter/search, trigger generation, update statuses, and download/view images. Uses table template patterns similar to content/tasks.
 
 ## Code Locations (exact paths)
 - Page: `frontend/src/pages/Writer/Images.tsx`
 - API: `frontend/src/services/api` (`fetchContentImages`, `fetchImageGenerationSettings`, `generateImages`, `bulkUpdateImagesStatus`, `deleteContent`, `bulkDeleteContent`)
 - Config: `frontend/src/config/pages/images.config` (columns/filters)
 - UI components: `frontend/src/components/common/ImageQueueModal`, `frontend/src/components/common/SingleRecordStatusUpdateModal`, `frontend/src/components/common/PageHeader`, `frontend/src/components/navigation/ModuleNavigationTabs`, `frontend/src/components/ui/modal`
 - Hooks: `frontend/src/hooks/useResourceDebug` (AI logs toggle), `frontend/src/hooks/useProgressModal` (via modal usage pattern)
 
 ## High-Level Responsibilities
 - Fetch and render content-image groups with client-side filtering/search/sorting/pagination.
 - Trigger image generation for selected content with queue modal and provider/model selection.
 - Update image status in bulk and delete images/content.
 - Provide AI function log visibility when resource debug is enabled.
 
 ## Detailed Behavior
 - Data load: `loadImages` calls `fetchContentImages({})`, applies client-side search (`content_title`) and status filter (`overall_status`), sorts (default `content_title`), paginates client-side (page size 10), and adds `id` field mirroring `content_id` for selection.
 - Filters: search text; status dropdown; sort controls; pagination tracked in local state.
 - Actions:
   - Generate images: opens `ImageQueueModal`, builds queue items, calls `generateImages` with provider/model; tracks taskId/model/provider state; shows AI logs when resource debug enabled.
   - Bulk status update: `bulkUpdateImagesStatus` on selected ids.
   - Delete (single/bulk): uses `deleteContent`/`bulkDeleteContent`.
   - Download/view: handled by row actions in config (template-driven).
 - Navigation: writer tabs rendered via `ModuleNavigationTabs` (Queue/Drafts/Images/Review/Published).
 - Resource debug: AI logs captured only when `useResourceDebug` returns true; `addAiLog` appends logs for visibility.
 - Loading UX: `loading` + `showContent` gating; debounced search resets page as needed.
 
 ## Data Structures / Models Involved (no code)
 - `ContentImagesGroup`: content_id, content_title, overall_status, images[].
 - `ContentImage`: individual image entries with URL/status/prompt (from API).
 - Generation settings: provider/model options from `fetchImageGenerationSettings`.
 
 ## Execution Flow
 - `useEffect` → `loadImages`.
 - Filters/sort/page changes → recompute client-side subsets.
 - Generate action → open modal → call `generateImages` → optionally log steps → reload images.
 - Status update/delete actions → call API → reload.
 
 ## Cross-Module Interactions
 - Tied to writer content records; delete actions use writer content endpoints.
 - AI generation leverages shared API endpoints that consume credits server-side.
 
 ## State Transitions
 - `loading`/`showContent` manage render timing; modal open states for queue/status/image viewer.
 - `aiLogs` maintained only when debug is enabled.
 
 ## Error Handling
 - Toast errors for load/generate/update/delete; generation errors also recorded in AI logs when enabled.
 - Debounced search handles errors gracefully by keeping prior data until reload.
 
 ## Tenancy Rules
 - Backend enforces account/site/sector; client passes no explicit tenant fields beyond any default filters in API layer.
 
 ## Billing Rules (if applicable)
 - Image generation consumes credits on backend; page performs no credit gating.
 
 ## Background Tasks / Schedulers (if applicable)
 - None; generation is user-triggered, and polling is not used here.
 
 ## Key Design Considerations
 - Client-side pagination used because API returns grouped images; keeps UI responsive without extra endpoints.
 - Resource debug toggle avoids unnecessary log storage unless explicitly enabled.
 
 ## How Developers Should Work With This Module
 - If server adds server-side pagination/filtering, remove client-side slicing and pass filters to API.
 - Extend row actions by updating `images.config` with handlers wired to new behaviors.
 - Keep generation flow in sync with backend provider/model options; surface credit estimates if backend exposes them.
 # Content Editor Page
 
 ## Purpose
 Display a single content record with full details for review/read-only inspection. Acts as the per-record viewer for content generated or managed by the Writer module.
 
 ## Code Locations (exact paths)
 - Page: `frontend/src/pages/Writer/ContentView.tsx`
 - Template: `frontend/src/templates/ContentViewTemplate` (renders the actual layout/content fields)
 - API: `frontend/src/services/api` (`fetchContentById`)
 
 ## High-Level Responsibilities
 - Fetch a specific content item by id from route param and render it via `ContentViewTemplate`.
 - Validate id parameter, handle not-found/error states, and provide back navigation to content list.
 
 ## Detailed Behavior
 - Route: `/writer/content/:id`.
 - On mount: validates `id` is numeric; on invalid, shows toast and redirects to `/writer/content`.
 - Fetches content via `fetchContentById(contentId)`; sets `content` state and clears `loading`.
 - Errors: shows toast (`Failed to load content`) and leaves `content` null.
 - Back action: `onBack` navigates to `/writer/content`.
 - Page metadata: sets document title/description via `PageMeta`.
 
 ## Data Structures / Models Involved (no code)
 - Content DTO from writer API (includes title, body/html, status, external_url, etc.; structure defined server-side).
 
 ## Execution Flow
 - `useEffect` → validate id → fetch content → update state → render template.
 - Template receives `{ content, loading, onBack }`.
 
 ## Cross-Module Interactions
 - Navigation back to writer drafts list; no direct cross-module calls.
 
 ## State Transitions
 - `loading` toggles during fetch; `content` set on success; invalid id triggers navigation away.
 
 ## Error Handling
 - Toast errors for missing/invalid id or fetch failure; console logs errors.
 
 ## Tenancy Rules
 - Backend enforces account/site/sector scoping; client only supplies id from route.
 
 ## Billing Rules (if applicable)
 - None within this view; generation/updates handled elsewhere.
 
 ## Background Tasks / Schedulers (if applicable)
 - None.
 
 ## Key Design Considerations
 - Strict id validation avoids bad requests.
 - Keeps view read-only; editing handled elsewhere (not in this component).
 
 ## How Developers Should Work With This Module
 - If adding inline editing, extend `ContentViewTemplate` and add PATCH/PUT calls; keep id validation and error handling intact.
