import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    window.setNavIndicator("nav .agent-call-nav-item.active", '#agent-call-marker', true, false)
    this.enableChatBubble()
  }

  hideAll() {
    document.querySelector("[id*='details_service_request']").classList.add("hidden")
    document.querySelector("[id*='chat_service_request']").classList.add("hidden")
    document.querySelector("[id*='all_service_requests_service_request']").classList.add("hidden")
  }

  showDetails(event) {
    this.hideAll()
    document.querySelector("[id*='details_service_request']").classList.remove("hidden")
    this.toggleActiveClass(event)
    window.setNavIndicator("nav .agent-call-nav-item.active", '#agent-call-marker', true, false)
  }

  showChat(event) {
    this.hideAll()
    this.hideChatBubble()
    document.querySelector("[id*='chat_service_request']").classList.remove("hidden")
    this.toggleActiveClass(event)
    window.setNavIndicator("nav .agent-call-nav-item.active", '#agent-call-marker', true, false)
    const chat = document.querySelector("#agent_sidebar")
    chat.scrollTop = chat.scrollHeight
    document.querySelector("#message_text").select()
  }

  showOtherRequests(event) {
    this.hideAll()
    document.querySelector("[id*='all_service_requests_service_request']").classList.remove("hidden")
    this.toggleActiveClass(event)
    window.setNavIndicator("nav .agent-call-nav-item.active", '#agent-call-marker', true, false)
  }

  enableChatBubble(event) {
    const chatTabItem = document.querySelector(".agent-call-nav-chat-item")
    chatTabItem.querySelector(".bubble").classList.add("enabled")
  }

  hideChatBubble(event) {
    const chatTabItem = document.querySelector(".agent-call-nav-chat-item")
    chatTabItem.querySelector(".bubble").classList.add("hidden")
  }

  toggleActiveClass(event) {
    document.querySelectorAll('nav .agent-call-nav-item').forEach(item => {
      item.classList.remove("active")
    })
    event.target.closest("button").classList.add("active")
  }
}
