'use client';

import React, { useRef } from 'react';
import RichTextEditor, { RichTextEditorHandle } from '@/components/RichTextEditor';
import { useProjectContext } from '@/providers/ProjectProvider';
import api from '@/lib/api';

export default function WritePage() {
    const editorRef = useRef<RichTextEditorHandle>(null);
    const { project, user, currentChapterId, updateChapter, incrementUsage } = useProjectContext();

    if (!currentChapterId) return null;

    const currentChapter = project.chapters?.find(c => c.id === currentChapterId);

    return (
        <RichTextEditor
            ref={editorRef}
            initialContent={currentChapter?.content || ''}
            onSave={(html) => updateChapter(currentChapterId, { content: html })}
            onAiTransform={async (text, mode) => {
                const result = await api.ai.transform(text, mode, currentChapter?.content || '', user);
                incrementUsage();
                return result;
            }}
        />
    );
}
