import { ContentEditable } from "@common/components/ContentEditable";
import { useAppState } from "../contexts/state";
import styles from '../assets/editor.module.css';
import { highlight } from "../utils/highlight";
import { useMemo } from "preact/hooks";

export const Editor = () => {
    const { currentStory, dispatch } = useAppState();

    if (!currentStory) {
        return <div class={styles.editor} />;
    }

    const handleInput = (e: Event) => {
        const text = (e.target as HTMLElement).textContent || '';
        dispatch({
            type: 'EDIT_STORY',
            id: currentStory.id,
            text,
        });
    };

    const value = useMemo(() => highlight(currentStory.text), [currentStory.text]);

    return (
        <div class={styles.editor}>
            <div class={styles.title}>{currentStory.title}</div>
            <ContentEditable
                class={styles.editable}
                value={value}
                onInput={handleInput}
            />
        </div>
    );
};
