import React, { useState } from 'react' import { useParams, useNavigate } from 'react-router-dom' import { ArrowLeft, BookOpen } from 'lucide-react' import { useAuthStore } from '../../store/authStore' import { useStoryStore } from '../../store/storyStore' import { useUIStore } from '../../store/uiStore' import { Button } from '../../components/ui/Button' import { Chapter } from '../../types' export const CreateChapterPage: React.FC = () => { const { storyId } = useParams<{ storyId: string }>() const navigate = useNavigate() const { currentUser } = useAuthStore() const { stories, chapters, addChapter } = useStoryStore() const { addToast } = useUIStore() const [form, setForm] = useState({ title: '', content: '' }) const [errors, setErrors] = useState>({}) const [loading, setLoading] = useState(false) const story = stories.find(s => s.story_id === Number(storyId)) const storyChapters = chapters.filter(c => c.story_id === Number(storyId)) const wordCount = form.content.trim().split(/\s+/).filter(Boolean).length if (!story) { return (

Story not found

) } const validate = () => { const e: Record = {} if (!form.title.trim()) e.title = 'Chapter title is required' if (!form.content.trim()) e.content = 'Chapter content is required' if (wordCount < 10) e.content = 'Chapter must be at least 10 words' setErrors(e) return Object.keys(e).length === 0 } const handleSubmit = async (isPublished: boolean) => { if (!validate() || !currentUser) return setLoading(true) await new Promise(r => setTimeout(r, 400)) const chapter: Chapter = { chapter_id: Date.now(), story_id: Number(storyId), title: form.title.trim(), content: form.content.trim(), chapter_number: storyChapters.length + 1, word_count: wordCount, view_count: 0, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), is_published: isPublished, } try { await addChapter(chapter) } catch (err: any) { const msg = err?.response?.data?.message || err?.message || 'Failed to save chapter.' addToast(msg, 'error') setLoading(false) return } addToast(isPublished ? 'Chapter published!' : 'Chapter saved as draft!') navigate(isPublished ? `/story/${storyId}` : `/writer/edit-story/${storyId}`) setLoading(false) } return (

{story.title}

New Chapter

Chapter {storyChapters.length + 1}

{ setForm(f => ({ ...f, title: e.target.value })); setErrors(e => ({ ...e, title: '' })) }} placeholder="The Awakening..." className={`w-full px-4 py-3 bg-slate-800 border rounded-xl text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500 font-serif text-lg ${errors.title ? 'border-rose-500' : 'border-slate-700'}`} /> {errors.title &&

{errors.title}

}
100 ? 'text-emerald-400' : wordCount > 50 ? 'text-amber-400' : 'text-slate-500'}> {wordCount.toLocaleString()} words