<template>
  <!-- Original Search Popup Design with Chat Functionality -->
  <div class="popup-search-box" :class="{ 'd-none': !isOpen, 'd-lg-block': true }" @click="preventOverlayClose">
    <button class="searchClose" @click="closeChat"><i class="fal fa-times"></i></button>
    
    <!-- Chat Messages Area (shows when there are messages) -->
    <div v-if="messages.length > 0" class="chat-messages-area" ref="chatBody">
      <div class="chat-messages-container">
        <!-- Chat Messages -->
        <div v-for="message in messages" :key="message.id" :class="['chat-message', message.sender]">
          <!-- AI Message -->
          <div v-if="message.sender === 'ai'" class="ai-message-bubble">
            <div class="message-avatar">
              <img src="/images/animation/bubble.gif" alt="D-Hero AI" width="28" height="28" style="border-radius: 50%;" />
            </div>
            <div class="message-content">
              <div class="bubble ai-bubble">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
          
          <!-- User Message -->
          <div v-else class="user-message-bubble">
            <div class="message-content">
              <div class="bubble user-bubble">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>

        <!-- Loading Message -->
        <div v-if="isLoading" class="chat-message ai">
          <div class="ai-message-bubble">
            <div class="message-avatar">
              <img src="/images/animation/bubble.gif" alt="D-Hero AI" width="28" height="28" style="border-radius: 50%;" />
            </div>
            <div class="message-content">
              <div class="bubble ai-bubble">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Search/Chat Input Form (always at bottom) -->
    <form @submit.prevent="sendMessage" :class="{ 'chat-mode': messages.length > 0 }">
      <input 
        v-model="currentMessage"
        type="text" 
        :placeholder="messages.length === 0 ? 'Ask D-Hero AI anything about health...' : 'Continue chatting...'"
        :disabled="isLoading"
        ref="chatInput"
      />
      <button type="submit" :disabled="!currentMessage.trim() || isLoading">
        <i v-if="!isLoading" class="fal fa-paper-plane"></i>
        <i v-else class="fal fa-circle-notch fa-spin"></i>
      </button>
      <!-- <span>D-Hero Ai is under development and may give inaccurate information if your problem is not solved or 
        if you are harmed<br>by suggested treatment we are not responsible and you should seek professional medical advice
      </span> -->
      </form>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue'

// Props
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['close'])

// Reactive data
const messages = ref([])
const currentMessage = ref('')
const isLoading = ref(false)
const conversationId = ref(null)

// Refs
const chatBody = ref(null)
const chatInput = ref(null)

// Methods
const closeChat = () => {
  emit('close')
}

const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value) return

  const userMessage = {
    id: Date.now(),
    sender: 'user',
    content: currentMessage.value,
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const messageToSend = currentMessage.value
  currentMessage.value = ''
  isLoading.value = true

  // Scroll to bottom after adding user message
  await nextTick()
  scrollToBottom()

  try {
    const response = await fetch('/api/ai-chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify({
        message: messageToSend,
        conversation_id: conversationId.value
      })
    })

    const data = await response.json()

    if (data.success) {
      const aiMessage = {
        id: Date.now() + 1,
        sender: 'ai',
        content: data.message,
        timestamp: new Date(data.timestamp)
      }
      
      messages.value.push(aiMessage)
      conversationId.value = data.conversation_id
    } else {
      throw new Error(data.error || 'Failed to get response')
    }
  } catch (error) {
    console.error('Chat error:', error)
    const errorMessage = {
      id: Date.now() + 1,
      sender: 'ai',
      content: 'Sorry, I encountered an error. Please try again.',
      timestamp: new Date()
    }
    messages.value.push(errorMessage)
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
  }
}

const scrollToBottom = () => {
  if (chatBody.value) {
    chatBody.value.scrollTop = chatBody.value.scrollHeight
  }
}

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

const preventOverlayClose = (event) => {
  // Prevent popup from closing when clicking inside the popup content
  // Override the template's jQuery click handler that closes on overlay click
  event.stopPropagation()
  event.preventDefault()
}

// Watch for prop changes
watch(() => props.isOpen, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (chatInput.value) {
        chatInput.value.focus()
      }
      scrollToBottom()
      
      // Override template's jQuery overlay click behavior
      // Remove the jQuery click handler that closes popup on overlay click
      $('.popup-search-box').off('click.searchOverlay')
    })
  }
})

// On mounted, also disable the template's overlay close behavior
onMounted(() => {
  // Disable template's jQuery overlay click handler
  if (typeof $ !== 'undefined') {
    $(document).ready(() => {
      $('.popup-search-box').off('click')
      // Only allow close button to close
      $('.searchClose').on('click', (e) => {
        e.preventDefault()
        e.stopPropagation()
        $('.popup-search-box').removeClass('show')
      })
    })
  }
})
</script>

<style>
/* Use existing template styles for popup-search-box */
.popup-search-box {
  /* Keep original template styles, just add chat functionality */
}

/* Chat Messages Area */
.chat-messages-area {
  position: absolute;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  width: 95%;
  max-width: 1200px;
  max-height: 800px;
  background: transparent;
  backdrop-filter: none;
  border-radius: 15px;
  padding: 20px;
  overflow-y: auto;
  box-shadow: none;
  border: none;
}

.chat-messages-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* Chat Message Styling */
.chat-message {
  display: flex;
  width: 100%;
}

.ai-message-bubble {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  justify-content: flex-start;
  max-width: 80%;
}

.user-message-bubble {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  max-width: 80%;
  margin-left: auto;
}

.message-avatar {
  flex-shrink: 0;
}

.message-avatar img {
  border: 2px solid #4caf4f00;
}

/* User avatar removed */

.message-content {
  flex: 1;
}

.bubble {
  padding: 12px 16px;
  border-radius: 18px;
  margin-bottom: 5px;
  word-wrap: break-word;
  position: relative;
}

.ai-bubble {
  background: rgba(240, 242, 247, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #333;
  border-bottom-left-radius: 5px;
}

.user-bubble {
  background: #4d7b6b;
  backdrop-filter: blur(10px);
  color: white;
  border-bottom-right-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.message-time {
  font-size: 11px;
  color: #f2ebeb;
  margin-top: 3px;
  opacity: 0.7;
}

.user-message-bubble .message-time {
  text-align: right;
  color: #f2ebeb;
}

/* Typing Indicator */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #4caf4f00;
  animation: typing-bounce 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing-bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-8px);
  }
}

/* Override initial search position only in chat mode */
.popup-search-box.show form.chat-mode {
  transform: translate(-50%, 500%) scale(1) !important;
}

/* Form Styling */
form.chat-mode {
  position: fixed;
  bottom: 20px;
  left: 50%;
  height: 4.5rem;
  transform: translateX(-50%);
  width: 95%;
  max-width: 800px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 25px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* Enhance form input when in chat mode */
form.chat-mode input {
  background: transparent;
  border: none;
  box-shadow: none;
}

form.chat-mode input:focus {
  background: transparent;
  border: none;
  border-radius: 25px;
  outline: none;
}

form.chat-mode button {
  background: linear-gradient(135deg, #4caf4f00, #45a04900);
  border: none;
  transition: all 0.3s ease;
}

form.chat-mode button:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
}

form.chat-mode button:disabled {
  transform: none;
  box-shadow: none;
}

/* Scrollbar Styling */
.chat-messages-area::-webkit-scrollbar {
  width: 6px;
}

.chat-messages-area::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.chat-messages-area::-webkit-scrollbar-thumb {
  background: rgba(76, 175, 80, 0.5);
  border-radius: 3px;
}

.chat-messages-area::-webkit-scrollbar-thumb:hover {
  background:#4d7b6b;
}

/* Responsive Design */
@media (max-width: 768px) {
  .chat-messages-area {
    width: 95%;
    bottom: 90px;
    padding: 15px;
  }
  
  .ai-message-bubble,
  .user-message-bubble {
    max-width: 90%;
  }
  
  .bubble {
    padding: 10px 14px;
    font-size: 14px;
  }

  form.chat-mode {
    width: 95%;
    bottom: 10px;
  }
}

/* Glass effect enhancement */
.popup-search-box::before {
  backdrop-filter: blur(15px);
}


</style>