<template>
    <div class="chat-widget">
        <!-- Chat Button -->
        <div
            :class="['chat-button', 'fixed bottom-5 right-5', { 'bounce-gentle': !isOpen }]"
            @click="toggleChat"
        >
            <div class="chat-button-circle" :style="{backgroundColor: widgetConfig.bubble_background_color}">
                <svg class="chat-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
            </div>
            <!-- Notification Badge -->
            <div v-if="unreadCount > 0" class="notification-badge">{{ unreadCount }}</div>
        </div>

        <!-- Chat Window -->
        <div
            :class="['chat-window', 'fixed bottom-20 right-5', { 'hidden': !isOpen }]"
        >
            <!-- Chat Header -->
            <div class="chat-header"
                 :style="{ backgroundColor: widgetConfig.chat_bar_header_bg_color, color: widgetConfig.chat_bar_header_text_color }">
                <div class="chat-header-info">
                    <div class="chat-avatar">
                        <img v-if="widgetConfig.agent_avatar_url" :src="widgetConfig.agent_avatar_url"
                             :alt="widgetConfig.agent_name"
                             style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;"/>
                        <span v-else>👤</span>
                    </div>
                    <div>
                        <div class="chat-title">{{ widgetConfig.agent_name }}</div>
                        <div class="chat-status">{{ widgetConfig.online_indicator_text }}</div>
                    </div>
                </div>
                <div class="header-actions">
                    <!-- Three-dot menu -->
                    <div class="menu-container" ref="menuContainer">
                        <button @click="toggleMenu" class="menu-btn text-white" :class="{ active: showMenu }">
                            ⋮
                        </button>
                        <div v-if="showMenu" class="menu-dropdown">
                            <button @click="confirmEndSession" class="menu-item">
                                <span class="menu-icon">🔄</span>
                                <span>End Session</span>
                            </button>
                        </div>
                    </div>
                    <button @click="closeChat" class="close-button">×</button>
                </div>
            </div>

            <!-- Chat Content -->
            <div class="chat-content" :style="{ backgroundColor: '#ffffff' }">
                <!-- Chat Messages -->
                <div class="chat-messages" ref="messagesContainer">
                    <!-- Initial Messages -->
                    <div class="message support">
                        <div class="message-avatar support">👤</div>
                        <div>
                            <div class="message-bubble support"
                                 :style="{ backgroundColor: widgetConfig.agent_chat_bg_color, color: widgetConfig.agent_chat_text_color }">
                                {{ widgetConfig.greeting_message }}
                            </div>
                            <div class="message-time">{{ getCurrentTime() }}</div>
                        </div>
                    </div>

                    <!-- Loading History Indicator -->
                    <MessageLoading v-if="isLoadingHistory"/>

                    <!-- Dynamic Messages -->
                    <MessageContainer :messages="messages"/>

                    <!-- Typing Indicator -->
                    <TypingIndicator v-if="isTyping"/>
                </div>

                <!-- Contact Form (for public users) -->
                <div v-if="showContactForm" class="contact-form-overlay">
                    <div class="contact-form">
                        <h3 class="contact-form-title">Start Conversation</h3>
                        <p class="contact-form-subtitle">Please provide your details to continue</p>

                        <div v-if="contactError" class="contact-error">
                            {{ contactError }}
                        </div>

                        <div class="contact-form-fields">
                            <div class="form-field">
                                <label for="contact-name">Name</label>
                                <input
                                    id="contact-name"
                                    v-model="contactForm.name"
                                    type="text"
                                    placeholder="Your name"
                                    class="contact-input"
                                    :disabled="isSubmittingContact"
                                />
                            </div>

                            <div class="form-field">
                                <label for="contact-email">Email</label>
                                <input
                                    id="contact-email"
                                    v-model="contactForm.email"
                                    type="email"
                                    placeholder="your@email.com"
                                    class="contact-input"
                                    :disabled="isSubmittingContact"
                                />
                            </div>
                        </div>

                        <div class="contact-form-actions">
                            <button
                                @click="cancelContactForm"
                                class="contact-btn contact-btn-cancel"
                                :disabled="isSubmittingContact"
                            >
                                Cancel
                            </button>
                            <button
                                @click="handleSendMessageWithContactForm"
                                class="contact-btn contact-btn-submit"
                                :disabled="!contactForm.name.trim() || !contactForm.email.trim() || isSubmittingContact"
                            >
                                <span v-if="isSubmittingContact">Starting...</span>
                                <span v-else>Start Chat</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Chat Input -->
                <div class="chat-input-area">
                    <div class="chat-input-container">
                        <input
                            type="text"
                            class="chat-input"
                            :placeholder="$t('Type your message...')"
                            v-model="currentMessage"
                            @keypress.enter="handleSendMessage"
                            ref="messageInput"
                        />
                        <button
                            class="send-button"
                            :style="{ backgroundColor: widgetConfig.send_button_color, color: widgetConfig.send_button_text_color }"
                            @click="handleSendMessage"
                            :disabled="isDisabledSubmitButton"
                        >
                            ➤
                        </button>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="chat-footer">
                <div class="footer-text">
                    <a href="http://chatbotwp.ai/" target="_blank">Powered by Zeno Chatbot</a>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import TypingIndicator from '@/Public/js/components/TypingIndicator.vue'
import { ref, nextTick, onMounted, onUnmounted, computed } from 'vue'
import { useWidgetConfig } from '@/Public/js/useWidgetConfig.js'
import { useCookie } from '@/Public/js/useCookie.js'
import MessageLoading from '@/Public/js/components/MessageLoading.vue';
import MessageContainer from '@/Public/js/components/MessageContainer.vue';

const { widgetConfig } = useWidgetConfig();
import { useAjax } from '../useAjax.js';

const { httpRequest } = useAjax()

// State
const isOpen = ref(false)
const unreadCount = ref(0)
const currentMessage = ref('')
const messages = ref([])
const isTyping = ref(false)
const messagesContainer = ref(null)
const messageInput = ref(null)
const { session_id, conversation_id, hasExistingSession, clearSession, refreshSession } = useCookie()
const isSessionInitialized = ref(false)
const isLoadingHistory = ref(false)
// Local flag to handle HttpOnly cookie cases (session info via API)
const sessionExists = ref(false)
const isDisabledSubmitButton = computed(() => !currentMessage.value.trim())

const handleSendMessage = async () => {

    const dataPayload = {
        message: currentMessage.value.trim()
    };

    if (hasExistingSession()) {
        dataPayload.session_id = session_id.value;
        dataPayload.conversation_id = conversation_id.value;
        return handleSendMessageRequest(dataPayload);
    }

    if (window.zenoChatbot.is_authenticated === 'yes') {
        return handleSendMessageRequest(dataPayload);
    }

    showContactFormModal();

};

const handleSendMessageWithContactForm = async () => {

    if (!contactForm.value.name.trim() || !contactForm.value.email.trim()) {
        contactError.value = 'Please fill in all fields'
        return
    }

    // Basic email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(contactForm.value.email)) {
        contactError.value = 'Please enter a valid email address'
        return
    }

    const payload = {
        message: currentMessage.value.trim(),
        name: contactForm.value.name,
        email: contactForm.value.email
    };

    isSubmittingContact.value = true
    contactError.value = ''

    try {
        await handleSendMessageRequest(payload);
        showContactForm.value = false
        contactForm.value = { name: '', email: '' }
        pendingMessage.value = '' // Clear pending message
        sessionExists.value = true
    } catch (error) {
        contactError.value = 'Failed to start conversation. Please try again.'
    } finally {
        isSubmittingContact.value = false;
        refreshSession();
    }
};


const handleSendMessageRequest = async (payload) => {

    isTyping.value = true
    scrollToBottom();

    addMessage(payload.message, true)
    currentMessage.value = ''

    try {

        const response = await httpRequest('zenochatbot_chat', payload);

        if (response.success) {
            addMessage(response.data.message, false)
        } else {
            addMessage(response.data, false)
        }

    } catch (e) {
        let errorMesage = e.message || window.zenoChatbot.error_response || 'Sorry, I encountered an error. Please try again.';
        addMessage(errorMesage, false)
    } finally {
        isTyping.value = false
    }
}

// Menu state
const showMenu = ref(false)
const menuContainer = ref(null)

// Contact form state (for public users)
const showContactForm = ref(false)
const contactForm = ref({
    name: '',
    email: ''
})
const contactError = ref('')
const isSubmittingContact = ref(false)
const pendingMessage = ref('') // Store the user's message while collecting contact info

// Methods
const toggleChat = async () => {

    isOpen.value = !isOpen.value

    if (isOpen.value) {
        unreadCount.value = 0

        // Initialize session and load history on first open
        if (!isSessionInitialized.value) {
            await initializeSession()
        }

        nextTick(() => {
            if (messageInput.value) {
                messageInput.value.focus()
            }
        })
    }
}

const closeChat = () => {
    isOpen.value = false
    showMenu.value = false // Close menu when closing chat
}

// Menu functions
const toggleMenu = () => {
    showMenu.value = !showMenu.value
}

const confirmEndSession = () => {

    if (confirm('Are you sure you want to end this session? This will clear all messages and start fresh.')) {
        endSession()
    }

    showMenu.value = false
}

const endSession = async () => {

    try {
        await httpRequest('zeno_chatbot_session_end', {});
    } catch (e) {
        //
    } finally {
        clearSession()
        messages.value = []
        isSessionInitialized.value = false
    }
}

const getCurrentTime = () => {
    const now = new Date()
    return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

const scrollToBottom = () => {
    // Scroll to bottom after next DOM update
    nextTick(() => {
        if (messagesContainer.value) {
            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
    })
}

const addMessage = (text, isUser = false) => {
    const message = {
        id: Date.now() + Math.random(),
        text,
        isUser,
        time: getCurrentTime()
    }
    messages.value.push(message)
    scrollToBottom()
}

const initializeSession = async () => {

    if (isSessionInitialized.value) return

    try {

        isLoadingHistory.value = true

        const response = await httpRequest('zenochatbot_history');


        if (response.success) {

            if (response.data.history && response.data.history.length > 0) {
                messages.value = response.data.history

                // Show loading indicator briefly
                setTimeout(() => {
                    scrollToBottom()
                }, 100)
            }
        }


    } finally {
        isSessionInitialized.value = true
        isLoadingHistory.value = false
    }
}

// Contact form functions
const showContactFormModal = () => {
    showContactForm.value = true
    contactError.value = ''
}

const cancelContactForm = () => {
    showContactForm.value = false
    contactForm.value = { name: '', email: '' }
    contactError.value = ''
    pendingMessage.value = '' // Clear pending message
}

const handleClickOutside = (event) => {
    if (menuContainer.value && !menuContainer.value.contains(event.target)) {
        showMenu.value = false
    }
}

// Click outside handler for menu
onMounted(() => {
    document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside)
})
</script>



