/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */
import { GoogleGenAI, Chat, GenerateContentResponse } from "@google/genai";

// Bheemax Software Solutions - Main script file

document.addEventListener('DOMContentLoaded', () => {
    console.log('Bheemax Software Solutions website loaded.');

    const mainHeader = document.getElementById('main-header');
    const menuToggle = document.querySelector('.menu-toggle') as HTMLButtonElement | null;
    const mainNav = document.getElementById('main-nav') as HTMLElement | null;
    const navUl = document.getElementById('main-nav-ul') as HTMLUListElement | null;

    // Hamburger Menu Toggle
    if (menuToggle && mainNav) {
        menuToggle.addEventListener('click', () => {
            const isExpanded = menuToggle.getAttribute('aria-expanded') === 'true' || false;
            menuToggle.setAttribute('aria-expanded', (!isExpanded).toString());
            mainNav.classList.toggle('nav-active');
        });

        // Close mobile nav on link click
        mainNav.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                if (mainNav.classList.contains('nav-active')) {
                    menuToggle.setAttribute('aria-expanded', 'false');
                    mainNav.classList.remove('nav-active');
                }
            });
        });
    }


    // Smooth scroll for navigation links
    document.querySelectorAll('a[href^="index.html#"], a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (this: HTMLAnchorElement, e: Event) {
            const href = this.getAttribute('href');
            if (!href) return;

            const isSamePageLink = href.startsWith('#');
            const isIndexLinkFromAnotherPage = href.startsWith('index.html#');
            const targetId = isIndexLinkFromAnotherPage ? href.substring(href.indexOf('#')) : href;

            if (targetId && targetId !== '#' && !targetId.endsWith('-placeholder')) {
                if (isIndexLinkFromAnotherPage && !window.location.pathname.endsWith('index.html') && window.location.pathname !== '/') {
                    return; 
                }
                
                e.preventDefault(); 

                const headerHeight = mainHeader ? mainHeader.offsetHeight : 0;
                const targetElement = document.querySelector(targetId) as HTMLElement | null;

                if (targetElement) {
                    const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
                    const offsetPosition = elementPosition - headerHeight;

                    window.scrollTo({
                        top: offsetPosition,
                        behavior: 'smooth'
                    });

                    if (navUl) {
                        navUl.querySelectorAll('a').forEach(navLink => navLink.classList.remove('active'));
                    }
                    const activeNavLink = navUl?.querySelector(`a[href$="${targetId}"]`);
                    activeNavLink?.classList.add('active');

                    // This part is now handled by the general nav link click listener above for mobile
                    // if (menuToggle && mainNav && mainNav.classList.contains('nav-active')) {
                    //     menuToggle.setAttribute('aria-expanded', 'false');
                    //     mainNav.classList.remove('nav-active');
                    // }
                }
            } else if (targetId && targetId.endsWith('-placeholder')) {
                e.preventDefault(); 
                console.log(`Placeholder link clicked: ${targetId}`);
                 // This part is now handled by the general nav link click listener above for mobile
                // if (menuToggle && mainNav && mainNav.classList.contains('nav-active')) {
                //     menuToggle.setAttribute('aria-expanded', 'false');
                //     mainNav.classList.remove('nav-active');
                // }
            }
        });
    });
    
    const scrollToSectionFromUrl = () => {
        if (window.location.hash && (window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname.includes('index.html#'))) {
            const targetId = window.location.hash;
            const headerHeight = mainHeader ? mainHeader.offsetHeight : 0;
            const targetElement = document.querySelector(targetId) as HTMLElement | null;

            if (targetElement) {
                setTimeout(() => {
                    const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
                    const offsetPosition = elementPosition - headerHeight;
                    window.scrollTo({
                        top: offsetPosition,
                        behavior: 'smooth'
                    });
                    if (navUl) {
                        navUl.querySelectorAll('a').forEach(navLink => navLink.classList.remove('active'));
                         const activeNavLink = navUl?.querySelector(`a[href$="${targetId}"]`);
                         activeNavLink?.classList.add('active');
                    }
                }, 100);
            }
        }
    };
    
    if (window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname.includes('index.html#')) {
        scrollToSectionFromUrl();
    }

    const currentYearSpan = document.getElementById('current-year');
    if (currentYearSpan) {
        currentYearSpan.textContent = new Date().getFullYear().toString();
    }

    if (window.location.pathname.endsWith('index.html') || window.location.pathname === '/') {
        const sections = document.querySelectorAll('main section');
        const navLinks = document.querySelectorAll('#main-nav ul li a');

        const updateActiveLinkOnScroll = () => {
            let currentSectionId = '';
            const headerHeight = mainHeader ? mainHeader.offsetHeight : 0;

            sections.forEach(section => {
                const sectionTop = section.getBoundingClientRect().top + window.pageYOffset - headerHeight - 50; 
                if (window.pageYOffset >= sectionTop) {
                    currentSectionId = section.getAttribute('id') || '';
                }
            });
            
            if (sections.length > 0 && window.pageYOffset < (sections[0] as HTMLElement).offsetTop / 2 && currentSectionId === '') {
                const heroLink = document.querySelector('#main-nav a[href$="#hero"]');
                if (heroLink) {
                    currentSectionId = 'hero';
                }
            }


            navLinks.forEach(link => {
                link.classList.remove('active');
                const href = link.getAttribute('href');
                if (href && href.endsWith(`#${currentSectionId}`)) {
                    link.classList.add('active');
                }
            });

            if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 100) { 
                const contactLink = document.querySelector('#main-nav a[href$="#contact"]');
                if(contactLink) {
                    navLinks.forEach(link => link.classList.remove('active'));
                    contactLink.classList.add('active');
                }
            }
        };

        window.addEventListener('scroll', updateActiveLinkOnScroll);
        updateActiveLinkOnScroll(); 
    }

    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', (e) => {
            e.preventDefault();
            alert('Login form submitted (placeholder).');
        });
    }

    const registerForm = document.getElementById('register-form');
    if (registerForm) {
        registerForm.addEventListener('submit', (e) => {
            e.preventDefault();
            alert('Registration form submitted (placeholder).');
        });
    }

    // --- Live Chat Functionality ---
    const chatToggleButton = document.getElementById('live-chat-toggle-button') as HTMLButtonElement;
    const chatWidget = document.getElementById('chat-widget') as HTMLDivElement;
    const chatCloseButton = document.getElementById('chat-widget-close-button') as HTMLButtonElement;
    const chatMessagesContainer = document.getElementById('chat-messages') as HTMLDivElement;
    const chatInputForm = document.getElementById('chat-input-form') as HTMLFormElement;
    const chatInput = document.getElementById('chat-input') as HTMLInputElement;
    const chatSendButton = document.getElementById('chat-send-button') as HTMLButtonElement;
    const loadingIndicator = document.getElementById('chat-loading-indicator') as HTMLDivElement;

    let ai: GoogleGenAI | null = null;
    let chatSession: Chat | null = null;
    let isChatInitialized = false;

    const systemInstruction = `You are a friendly and helpful customer support assistant for Bheemax Software Solutions.
Answer questions about our company, products (Idea Management, Issue Tracking), services (On-Prem, SaaS),
and industries we serve (Automobile, Banking, Power, Supply Chain, Marketing).
Keep your answers concise and helpful. Be polite and professional.
If you cannot answer a question or if it's outside your scope, politely say so and suggest contacting support directly at info@bheemax.com or visiting the website for more specific details.
Do not make up information you don't know.
Format your responses clearly. You can use simple markdown like bolding for emphasis if appropriate, but avoid complex structures.`;

    async function initializeChatSession() {
        if (!process.env.API_KEY) {
            console.error("API_KEY is not set. Chat cannot be initialized.");
            appendMessageToChat("Chat service is currently unavailable. API key missing.", 'ai');
            isChatInitialized = false; // Mark as not initialized or failed
            return;
        }
        ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
        chatSession = ai.chats.create({
            model: 'gemini-2.5-flash-preview-04-17',
            config: {
                systemInstruction: systemInstruction,
            }
        });
        isChatInitialized = true;
        console.log("Chat session initialized.");
        // Optional: Send an initial greeting from AI
        appendMessageToChat("Hello! I'm the Bheemax assistant. How can I help you today?", 'ai');
    }

    function toggleChatWidget(forceOpen?: boolean) {
        const isHidden = chatWidget.hasAttribute('hidden');
        if (forceOpen === true || isHidden) {
            chatWidget.removeAttribute('hidden');
            chatToggleButton.setAttribute('aria-expanded', 'true');
            chatInput.focus();
            if (!isChatInitialized) {
                initializeChatSession();
            }
        } else if (forceOpen === false || !isHidden) {
            chatWidget.setAttribute('hidden', '');
            chatToggleButton.setAttribute('aria-expanded', 'false');
        }
    }

    function appendMessageToChat(text: string, sender: 'user' | 'ai', isStreamingChunk: boolean = false, existingMessageElement: HTMLElement | null = null): HTMLElement {
        let messageElement: HTMLElement;
        let contentElement: HTMLElement;

        if (existingMessageElement) {
            messageElement = existingMessageElement;
            contentElement = messageElement.querySelector('.message-content') as HTMLElement;
            // Append text content for streaming
            contentElement.textContent += text;
        } else {
            messageElement = document.createElement('div');
            messageElement.classList.add('message', `${sender}-message`);
            
            contentElement = document.createElement('div');
            contentElement.classList.add('message-content');
            contentElement.textContent = text;
            messageElement.appendChild(contentElement);
            
            chatMessagesContainer.appendChild(messageElement);
        }
        
        // Scroll to bottom only after the full message or if it's a user message
        if (!isStreamingChunk || sender === 'user') {
            chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
        }
        return messageElement;
    }


    async function handleSendMessage(event?: Event) {
        if (event) event.preventDefault();
        const userInput = chatInput.value.trim();
        if (!userInput) return;

        appendMessageToChat(userInput, 'user');
        chatInput.value = '';
        chatInput.disabled = true;
        chatSendButton.disabled = true;
        loadingIndicator.style.display = 'flex';

        if (!isChatInitialized || !chatSession) {
            await initializeChatSession(); // Attempt to re-initialize if needed
            if (!isChatInitialized || !chatSession) { // Check again after attempt
                appendMessageToChat("I'm having trouble connecting to the chat service. Please try again in a moment.", 'ai');
                loadingIndicator.style.display = 'none';
                chatInput.disabled = false;
                chatSendButton.disabled = false;
                return;
            }
        }
        
        try {
            const stream = await chatSession.sendMessageStream({ message: userInput });
            let currentAiMessageElement: HTMLElement | null = null;
            let firstChunk = true;

            for await (const chunk of stream) {
                if (firstChunk) {
                    loadingIndicator.style.display = 'none';
                    // Create the initial AI message bubble with the first chunk
                    currentAiMessageElement = appendMessageToChat(chunk.text, 'ai', true);
                    firstChunk = false;
                } else if (currentAiMessageElement) {
                    // Append subsequent chunks to the existing AI message bubble
                    appendMessageToChat(chunk.text, 'ai', true, currentAiMessageElement);
                }
                 chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight; // Scroll as content streams
            }
            // Final scroll after all chunks are processed (if currentAiMessageElement exists)
            if (currentAiMessageElement) {
                 chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
            }
            if (firstChunk && !currentAiMessageElement) { // Stream was empty or no content
                 loadingIndicator.style.display = 'none';
                 appendMessageToChat("I received that, but I don't have a specific response right now.", 'ai');
            }

        } catch (error) {
            console.error("Error sending message to Gemini:", error);
            appendMessageToChat("Sorry, I encountered an error while trying to respond. Please try again.", 'ai');
            loadingIndicator.style.display = 'none';
        } finally {
            chatInput.disabled = false;
            chatSendButton.disabled = false;
            chatInput.focus();
        }
    }

    if (chatToggleButton && chatWidget && chatCloseButton && chatInputForm) {
        chatToggleButton.addEventListener('click', () => toggleChatWidget());
        chatCloseButton.addEventListener('click', () => toggleChatWidget(false));
        chatInputForm.addEventListener('submit', handleSendMessage);
    }

});

export {}; // Ensures this is treated as a module