async function initNotepadStory()

in src/gemini_95/index.ts [411:470]


async function initNotepadStory(windowElement: HTMLDivElement): Promise<void> {
    const textarea = windowElement.querySelector('.notepad-textarea') as HTMLTextAreaElement;
    const storyButton = windowElement.querySelector('.notepad-story-button') as HTMLButtonElement;

    if (!textarea || !storyButton) {
        console.error("Notepad elements not found in window:", windowElement.id);
        return;
    }

    storyButton.addEventListener('click', async () => {
        // Show "Generating story..." message
        const currentText = textarea.value;
        textarea.value = currentText + "\n\nGenerating story... Please wait...\n\n";
        textarea.scrollTop = textarea.scrollHeight;

        // Disable button while generating
        storyButton.disabled = true;
        storyButton.textContent = "Working...";

        try {
            // --- Initialize Gemini right before use if needed (matching gifmaker) ---
            if (!geminiInstance) {
                if (!await initializeGeminiIfNeeded('initNotepadStory')) {
                    throw new Error("Failed to initialize Gemini API for story generation");
                }
            }

            // Call the Gemini API to generate a story
            const prompt = "Write me a short creative story (250-300 words) with an unexpected twist ending. Make it engaging and suitable for all ages.";

            const result = await geminiInstance.models.generateContentStream({
                 model: 'gemini-1.5-flash',
                 contents: prompt,
             });

            // Replace the "Generating..." message with an empty string
            const textWithoutGenerating = currentText + "\n\n"; // Simpler replacement
            textarea.value = textWithoutGenerating;

            // Stream in the response
            for await (const chunk of result) {
                 const chunkText = chunk.text || "";
                 textarea.value += chunkText;
                 textarea.scrollTop = textarea.scrollHeight;
            }

            // Add a newline after the story
            textarea.value += "\n\n";

        } catch (error: any) {
                console.error("Error generating story:", error);
                textarea.value = currentText + "\n\nError: " + (error.message || "Failed to generate story.") + "\n\n";
        } finally {
            // Re-enable the button
            storyButton.disabled = false;
            storyButton.textContent = "Generate Story";
            textarea.scrollTop = textarea.scrollHeight;
        }
    });
}