/* eslint-disable no-undef */
;(function () {
  'use strict'

  const chatButton = document.querySelector('.sidebar .chat-btn')
  const chat = document.querySelector('.sidebar .chat')
  const chatIcon = document.querySelector('.sidebar .chat-btn svg')
  const chatTextArea = document.getElementById('chat-input')
  const sendButton = document.getElementById('send-btn')
  const chatBody = document.querySelector('.sidebar .chat .chat-body')
  const expandButton = document.querySelector('#expand-btn svg')

  let INIT = false
  let isComposing = false
  let isLoading = false
  const pathname = window.location.pathname.split('/')?.[3] || ''
  let docType = pathname !== 'swlab-docs' ? pathname : '' // 선택된 제품 유형을 저장할 변수

  const openIconPath = `
    <path stroke-linecap="round" stroke-linejoin="round"
    d="M7.188 10a.312.312 0 1 1-.625 0
    .312.312 0 0 1 .625 0Zm0 0h-.313m3.438 0a.312.312 0
    1 1-.625 0 .312.312 0 0 1 .625 0Zm0 0h-.313m3.437 0a.312.312 0
    1 1-.625 0 .312.312 0 0 1 .625 0Zm0 0h-.312M17.5 10c0 3.797-3.353
    6.875-7.5 6.875a8.735 8.735 0 0 1-2.292-.303 5.368 5.368 0 0 1-3.639
    1.576 5.364 5.364 0 0 1-.428-.059 4.025 4.025 0 0 0 .88-1.818c.081-.409
    -.12-.806-.422-1.098C3.273 13.484 2.5 11.825 2.5 10c0-3.797 3.353-6.875
    7.5-6.875s7.5 3.078 7.5 6.875Z"></path>
  `
  const closeIconPath = `
    <path clip-rule="evenodd" fill-rule="evenodd"
    d="M12.53 16.28a.75.75 0 0 1-1.06 0l-7.5-7.5a.75.75 0 0 1 1.06-1.06L12
    14.69l6.97-6.97a.75.75 0 1 1 1.06 1.06l-7.5 7.5Z"></path>
  `

  const collapseIconPath = `
    <path
    d="M3.28 2.22a.75.75 0 0 0-1.06 1.06L5.44 6.5H2.75a.75.75 0 0 0 0 1.5h4.5
    A.75.75 0 0 0 8 7.25v-4.5a.75.75 0 0 0-1.5 0v2.69L3.28 2.22ZM13.5 2.75
    a.75.75 0 0 0-1.5 0v4.5c0 .414.336.75.75.75h4.5a.75.75 0 0 0 0-1.5h-2.69l3.22-3.22
    a.75.75 0 0 0-1.06-1.06L13.5 5.44V2.75ZM3.28 17.78l3.22-3.22v2.69a.75.75 0 0 0 1.5
    0v-4.5a.75.75 0 0 0-.75-.75h-4.5a.75.75 0 0 0 0 1.5h2.69l-3.22 3.22a.75.75
    0 1 0 1.06 1.06ZM13.5 14.56l3.22 3.22a.75.75 0 1 0 1.06-1.06l-3.22-3.22h2.69
    a.75.75 0 0 0 0-1.5h-4.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0v-2.69Z">
    </path>
  `

  const expandIconPath = `
    <path d="
    m13.28 7.78 3.22-3.22v2.69a.75.75 0 0 0 1.5 0v-4.5a.75.75 0 0 0-.75-.75h-4.5a.75.75
    0 0 0 0 1.5h2.69l-3.22 3.22a.75.75 0 0 0 1.06 1.06ZM2 17.25v-4.5a.75.75 0 0 1 1.5 0v2.69l3.22-3.22a.75.75
    0 0 1 1.06 1.06L4.56 16.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.747.747 0 0 1-.75-.75ZM12.22
    13.28l3.22 3.22h-2.69a.75.75 0 0 0 0 1.5h4.5a.747.747 0 0 0 .75-.75v-4.5a.75.75
    0 0 0-1.5 0v2.69l-3.22-3.22a.75.75 0 1 0-1.06 1.06ZM3.5 4.56l3.22 3.22a.75.75
    0 0 0 1.06-1.06L4.56 3.5h2.69a.75.75 0 0 0 0-1.5h-4.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0V4.56Z">
    </path>
  `

  function initializeChat () {
    if (!INIT) {
      const messageItem = document.createElement('pre')
      const productList = document.createElement('ul') // ul 요소 생성
      const products = ['BXM', 'BXCM', 'BXCP', 'BXI']

      messageItem.className = 'message ai'
      messageItem.textContent = pathname === 'swlab-docs'
        ? '뱅크웨어글로벌 소프트웨어 연구소 챗봇입니다. 어떤 제품 가이드에 대한 질문을 하시겠습니까?'
        : `뱅크웨어글로벌 소프트웨어 연구소 챗봇입니다. ${pathname.toUpperCase()}제품 가이드에 대한 질문을 해주세요.`
      chatBody.appendChild(messageItem)

      if (pathname === 'swlab-docs') {
        products.forEach((product) => {
          const productItem = document.createElement('li')
          productItem.textContent = product
          productItem.addEventListener('click', () => {
            docType = product // 클릭한 제품명을 docType에 저장
            createAiMessage(`${docType} 가이드에 대한 도움을 드리겠습니다.`)
          })
          productList.appendChild(productItem)
        })

        chatBody.appendChild(productList)
      }

      INIT = true

      // Composition events
      chatTextArea.addEventListener('compositionstart', () => {
        isComposing = true
      })

      chatTextArea.addEventListener('compositionend', () => {
        isComposing = false
      })

      // Keydown event
      chatTextArea.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && !e.shiftKey && !isComposing && !isLoading) {
          e.preventDefault() // Prevent the default action of Enter (which is to create a new line)
          const { value } = e.target
          if (value.trim() !== '') {
            handleUserMessage(value)
          }
        }
      })

      sendButton.addEventListener('click', () => {
        if (!isLoading) {
          const message = chatTextArea.value
          handleUserMessage(message)
        }
      })
    }
  }

  chatButton.addEventListener('click', () => {
    chat.classList.toggle('show')

    if (chat.classList.contains('show')) {
      chatIcon.innerHTML = closeIconPath
      chatIcon.setAttribute('fill', 'none')
      chatIcon.setAttribute('stroke', '#fff')
      chatIcon.setAttribute('viewBox', '0 -1 24 24')
    } else {
      chatIcon.innerHTML = openIconPath
      chatIcon.setAttribute('fill', '#fff')
      chatIcon.setAttribute('stroke', '#0072ce')
      chatIcon.setAttribute('viewBox', '0 0 20 20')
    }

    if (!INIT) {
      initializeChat()
    }
  })

  expandButton.addEventListener('click', () => {
    expandButton.classList.toggle('expand')

    if (expandButton.classList.contains('expand')) {
      expandButton.innerHTML = collapseIconPath
      expandButton.setAttribute('fill', '#fff')
      expandButton.setAttribute('viewBox', '0 0 20 20')
      chat.classList.add('expand')
    } else {
      expandButton.innerHTML = expandIconPath
      expandButton.setAttribute('fill', '#fff')
      expandButton.setAttribute('viewBox', '0 0 20 20')
      chat.classList.remove('expand')
    }
  })

  function handleUserMessage (message) {
    if (message.trim() !== '') {
      addMessageToChatBody(message)
      chatTextArea.value = ''
    }
  }

  function addMessageToChatBody (message) {
    if (message.trim() !== '') {
      const user = document.createElement('pre')
      user.className = 'message user'
      user.textContent = message
      chatBody.appendChild(user)
      chatBody.scrollTop = chatBody.scrollHeight

      if (!docType) {
        createAiMessage('가이드 도움에 필요한 제품을 선택해주세요.')
        return
      }

      isLoading = true

      const messageItem = document.createElement('pre')
      messageItem.className = 'message ai'
      chatBody.appendChild(messageItem)
      chatBody.scrollTop = chatBody.scrollHeight

      const payload = {
        question: message,
        docsType: docType.toLowerCase(),
      }

      fetch('https://182.162.100.161/ask', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      })
        .then((response) => {
          const reader = response.body?.getReader()
          const decoder = new TextDecoder('utf-8')

          function readStream() {
            return reader?.read().then(({ done, value }) => {
              if (done) {
                isLoading = false
                return
              }
              const chunk = decoder.decode(value, { stream: true })
              messageItem.textContent += chunk
              chatBody.scrollTop = chatBody?.scrollHeight
              return readStream()
            })
          }

          return readStream()
        })
        .catch((error) => {
          console.error('Chatbot Error', error)
          isLoading = false
        })

      // const chatLoader = document.createElement('div')
      // chatLoader.className = 'chat-loader'
      // const loader = document.createElement('div')
      // loader.className = 'loader'
      // chatLoader.appendChild(loader)
      // chatBody.appendChild(chatLoader)
      // chatBody.scrollTop = chatBody.scrollHeight

      // setTimeout(() => {
      //   chatBody.removeChild(chatLoader)

      //   const ai = document.createElement('pre')
      //   ai.className = 'message ai'
      //   ai.textContent = '지금은 답해드릴 수 없어요.'
      //   chatBody.appendChild(ai)
      //   chatBody.scrollTop = chatBody.scrollHeight

      //   isLoading = false
      // }, 3000)
    }
  }

  function createAiMessage (message) {
    const messageItem = document.createElement('pre')
    messageItem.className = 'message ai'
    messageItem.textContent = message
    chatBody.appendChild(messageItem)
    chatBody.scrollTop = chatBody.scrollHeight
  }
})()