async function initGeminiChat()

in src/gemini_95/index.ts [320:408]


async function initGeminiChat(windowElement: HTMLDivElement): Promise<void> {
    const historyDiv = windowElement.querySelector('.gemini-chat-history') as HTMLDivElement;
    const inputEl = windowElement.querySelector('.gemini-chat-input') as HTMLInputElement;
    const sendButton = windowElement.querySelector('.gemini-chat-send') as HTMLButtonElement;

    if (!historyDiv || !inputEl || !sendButton) {
        console.error("Gemini chat elements not found in window:", windowElement.id);
        return;
    }

    function addChatMessage(container: HTMLDivElement, text: string, className: string = '') {
        const p = document.createElement('p');
        if (className) p.classList.add(className);
        p.textContent = text;
        container.appendChild(p);
        container.scrollTop = container.scrollHeight; // Scroll to bottom
    }

    addChatMessage(historyDiv, "Initializing AI...", "system-message");

    // --- Send Message Logic ---
    const sendMessage = async () => {
        // --- Initialize Gemini right before the first potential use (matching gifmaker) ---
        if (!geminiInstance) {
            const initSuccess = await initializeGeminiIfNeeded('initGeminiChat');
            if (!initSuccess) {
                console.error("Failed to initialize Gemini in initGeminiChat");
                addChatMessage(historyDiv, "Error: Failed to initialize AI. Check console for details.", "error-message");
                inputEl.disabled = false;
                sendButton.disabled = false;
                return;
            }
            
            const initMsg = Array.from(historyDiv.children).find(el => el.textContent?.includes("Initializing AI..."));
            if (initMsg) initMsg.remove();
            addChatMessage(historyDiv, "AI Ready.", "system-message");
        }

        const message = inputEl.value.trim();
        if (!message) return;

        addChatMessage(historyDiv, `You: ${message}`, "user-message");
        inputEl.value = '';
        inputEl.disabled = true;
        sendButton.disabled = true;

        try {
            const chat = geminiInstance.chats.create({
                model: 'gemini-1.5-flash',
                history: [],
            });
            const result = await chat.sendMessageStream({message: message});

            let fullResponse = "";
            addChatMessage(historyDiv, "Gemini: ", "gemini-message");
            const lastMessageElement = historyDiv.lastElementChild as HTMLParagraphElement | null;
            for await (const chunk of result) {
                 const chunkText = chunk.text || "";
                 fullResponse += chunkText;
                 if (lastMessageElement) {
                    lastMessageElement.textContent += chunkText;
                    historyDiv.scrollTop = historyDiv.scrollHeight;
                 }
            }
            console.log("Gemini full response:", fullResponse);
        } catch (error: any) {
             console.error("Error calling Gemini API:", error);
            addChatMessage(historyDiv, `Error: ${error.message || 'Failed to get response from Gemini.'}`, "error-message");
        } finally {
             inputEl.disabled = false;
            sendButton.disabled = false;
            inputEl.focus();
        }
    };

    // Event Listeners for sending message
    sendButton.onclick = sendMessage;
    inputEl.onkeydown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    };

    // Initial state - enable input/button after setup
    inputEl.disabled = false;
    sendButton.disabled = false;
    inputEl.focus();
}