import { computed, ref, watch } from 'vue'
import { useSiteStore } from '@/stores/site'

/**
 * 站点 Logo：图片加载失败时回退为站点名称首字母
 */
export function useSiteLogo(src?: () => string | undefined) {
  const siteStore = useSiteStore()
  const siteName = computed(() => siteStore.siteName || 'MES系统')
  const siteLogo = computed(() => src?.() ?? siteStore.siteLogo)
  const logoLoadFailed = ref(false)
  const showSiteLogoImg = computed(() => !!siteLogo.value && !logoLoadFailed.value)
  const fallbackLetter = computed(() => siteName.value.charAt(0) || 'M')

  watch(siteLogo, () => {
    logoLoadFailed.value = false
  })

  function handleLogoError() {
    logoLoadFailed.value = true
  }

  return {
    siteName,
    siteLogo,
    showSiteLogoImg,
    fallbackLetter,
    handleLogoError,
  }
}
