document.addEventListener("DOMContentLoaded", () => {
  // --- Element Selections ---
  const elements = {
    fabWidgetContainer: document.getElementById("fabWidgetContainer"),
    fabMainButton: document.getElementById("fabMainButton"),
    fabAiChatButton: document.getElementById("fabAiChatButton"),
    aiChatWindow: document.getElementById("aiChatWindow"),
    closeChatWindow: document.getElementById("closeChatWindow"),
    aiChatBody: document.getElementById("aiChatBody"),
    chatInput: document.getElementById("chatInput"),
    sendChatButton: document.getElementById("sendChatButton"),
    chatBackdrop: document.getElementById("chatBackdrop"),
    quickActions: document.querySelectorAll(".quick-action"),
  }

  const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")

  // --- Utility Functions ---
  const utils = {
    vibrate: (duration = 50) => {
      if (navigator.vibrate) {
        navigator.vibrate(duration)
      }
    },

    playSound: (sender) => {
      if ("AudioContext" in window) {
        try {
          const audioContext = new AudioContext()
          const oscillator = audioContext.createOscillator()
          const gainNode = audioContext.createGain()

          oscillator.connect(gainNode)
          gainNode.connect(audioContext.destination)

          oscillator.frequency.value = sender === "user" ? 800 : 600
          oscillator.type = "sine"

          gainNode.gain.setValueAtTime(0, audioContext.currentTime)
          gainNode.gain.linearRampToValueAtTime(0.1, audioContext.currentTime + 0.01)
          gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.1)

          oscillator.start(audioContext.currentTime)
          oscillator.stop(audioContext.currentTime + 0.1)
        } catch (error) {
          console.warn("Audio context error:", error)
        }
      }
    },

    formatTime: () => {
      return new Date().toLocaleTimeString("bn-BD", {
        hour: "2-digit",
        minute: "2-digit",
      })
    },

    scrollToBottom: () => {
      if (elements.aiChatBody) {
        elements.aiChatBody.scrollTop = elements.aiChatBody.scrollHeight
      }
    },
  }

  // --- FAB Logic ---
  const fab = {
    toggle: () => {
      if (elements.fabWidgetContainer) {
        elements.fabWidgetContainer.classList.toggle("active")
        utils.vibrate()
      }
    },

    close: () => {
      if (elements.fabWidgetContainer) {
        elements.fabWidgetContainer.classList.remove("active")
        utils.vibrate(30)
      }
    },
  }

  // --- AI Chat Window Logic ---
  const chat = {
    open: () => {
      if (elements.aiChatWindow && elements.chatBackdrop) {
        elements.aiChatWindow.classList.add("active")
        elements.chatBackdrop.classList.add("active")
        fab.close()

        setTimeout(() => {
          elements.chatInput?.focus()
        }, 300)
      }
    },

    close: () => {
      if (elements.aiChatWindow && elements.chatBackdrop) {
        elements.aiChatWindow.classList.remove("active")
        elements.chatBackdrop.classList.remove("active")
      }
    },

    appendMessage: (text, sender, isAnimated = true) => {
      if (!elements.aiChatBody) return

      const messageDiv = document.createElement("div")
      messageDiv.classList.add("message", sender)
      if (isAnimated) {
        messageDiv.classList.add("animate")
      }

      const avatarDiv = document.createElement("div")
      avatarDiv.classList.add("message-avatar")

      const avatarIcon =
        sender === "ai"
          ? `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
             <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
           </svg>`
          : `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
             <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
           </svg>`

      avatarDiv.innerHTML = avatarIcon

      const contentDiv = document.createElement("div")
      contentDiv.classList.add("message-content")

      const textDiv = document.createElement("div")
      textDiv.classList.add("message-text")
      textDiv.innerHTML = text.replace(/\n/g, "<br>")

      const timeDiv = document.createElement("div")
      timeDiv.classList.add("message-time")
      timeDiv.textContent = utils.formatTime()

      contentDiv.appendChild(textDiv)
      contentDiv.appendChild(timeDiv)
      messageDiv.appendChild(avatarDiv)
      messageDiv.appendChild(contentDiv)

      elements.aiChatBody.appendChild(messageDiv)
      utils.scrollToBottom()
      utils.playSound(sender)
    },

    showTypingIndicator: () => {
      if (!elements.aiChatBody) return

      const typingDiv = document.createElement("div")
      typingDiv.id = "typing-indicator"
      typingDiv.classList.add("typing-indicator")

      typingDiv.innerHTML = `
        <div class="message-avatar">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
          </svg>
        </div>
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
      `

      elements.aiChatBody.appendChild(typingDiv)
      utils.scrollToBottom()
    },

    hideTypingIndicator: () => {
      const typingIndicator = document.getElementById("typing-indicator")
      if (typingIndicator) {
        typingIndicator.remove()
      }
    },

    sendMessage: async (messageText = null) => {
      const text = messageText || elements.chatInput?.value.trim()
      if (!text || text === "") return

      chat.appendMessage(text, "user")
      if (!messageText && elements.chatInput) {
        elements.chatInput.value = ""
      }
      elements.chatInput?.focus()
      chat.showTypingIndicator()
      utils.vibrate(30)

      try {
        const response = await fetch("/api/ai-chat", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": csrfToken,
            Accept: "application/json",
          },
          body: JSON.stringify({ message: text }),
        })

        chat.hideTypingIndicator()

        if (!response.ok) {
          const errorData = await response.json()
          throw new Error(errorData.error || "সার্ভার এরর হয়েছে।")
        }

        const data = await response.json()

        setTimeout(() => {
          chat.appendMessage(data.reply, "ai")
        }, 500)
      } catch (error) {
        chat.hideTypingIndicator()
        console.error("Chat Error:", error)
        chat.appendMessage(`দুঃখিত, একটি সমস্যা হয়েছে: ${error.message}`, "ai")
      }
    },
  }

  // --- Event Listeners ---
  const eventListeners = {
    init: () => {
      // FAB Events
      elements.fabMainButton?.addEventListener("click", fab.toggle)

      // Chat Events
      elements.fabAiChatButton?.addEventListener("click", chat.open)
      elements.closeChatWindow?.addEventListener("click", chat.close)
      elements.chatBackdrop?.addEventListener("click", chat.close)
      elements.sendChatButton?.addEventListener("click", () => chat.sendMessage())

      // Input Events
      elements.chatInput?.addEventListener("keypress", (e) => {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault()
          chat.sendMessage()
        }
      })

      // Auto-resize input
      elements.chatInput?.addEventListener("input", function () {
        this.style.height = "auto"
        this.style.height = Math.min(this.scrollHeight, 100) + "px"
      })

      // Quick Actions
      elements.quickActions.forEach((button) => {
        button.addEventListener("click", () => {
          const message = button.getAttribute("data-message")
          chat.sendMessage(message)
        })
      })

      // Keyboard shortcuts
      document.addEventListener("keydown", (e) => {
        // ESC to close chat
        if (e.key === "Escape" && elements.aiChatWindow?.classList.contains("active")) {
          chat.close()
        }

        // Ctrl/Cmd + K to open chat
        if ((e.ctrlKey || e.metaKey) && e.key === "k") {
          e.preventDefault()
          if (!elements.aiChatWindow?.classList.contains("active")) {
            chat.open()
          }
        }
      })
    },
  }

  // --- Initialize ---
  const init = () => {
    eventListeners.init()

    // Add welcome animation after page load
    setTimeout(() => {
      if (elements.fabMainButton) {
        elements.fabMainButton.style.animation = "bounce 2s infinite"
      }
    }, 1000)

    console.log("🚀 AI Chat Widget initialized successfully!")
  }

  // Start the application
  init()
})
