import { defineStore } from "pinia"
import { ref, nextTick } from "vue"

export const useThemeStore = defineStore('theme', () => {
  const isDarkMode = ref(false)

  const toggleTheme = () => {
    isDarkMode.value = !isDarkMode.value
    localStorage.setItem("chatTheme", isDarkMode.value ? "dark" : "light")
    updateTheme()
  }

  // 修改：仅针对.chat-box-body元素应用主题
  const updateTheme = () => {
    nextTick(() => {
      const chatBoxBody = document.querySelector('.chat-box-body')
      if (!chatBoxBody) return

      if (isDarkMode.value) {
        chatBoxBody.setAttribute("data-theme", "dark")
        chatBoxBody.classList.add("dark")
      } else {
        chatBoxBody.removeAttribute("data-theme")
        chatBoxBody.classList.remove("dark")
      }
    })
  }

  // 修改：确保DOM就绪后再加载主题
  const loadTheme = () => {
    const savedTheme = localStorage.getItem("chatTheme")
    if (savedTheme) {
      isDarkMode.value = savedTheme === "dark"
    } else {
      isDarkMode.value = window.matchMedia?.("(prefers-color-scheme: dark)").matches
    }

    // 等待DOM渲染完成后再更新主题
    const applyTheme = () => {
      if (document.querySelector('.chat-box-body')) {
        updateTheme()
      } else {
        requestAnimationFrame(applyTheme)
      }
    }
    applyTheme()
  }

  return {
    isDarkMode,
    toggleTheme,
    loadTheme,
  }
})
