import { reactive, watch } from 'vue'
import { getFileUrl } from '@/utils/config'

interface SiteConfig {
  siteName: string
  siteDescription: string
  logoLight: string
  logoDark: string
  favicon: string
}

interface SiteSettings {
  siteName: string
  siteDescription: string
  siteLogo: string
  siteFavicon: string
  logoLight: string
  logoDark: string
}

const siteSettings = reactive<SiteSettings>({
  siteName: '',
  siteDescription: '',
  siteLogo: '',
  siteFavicon: '',
  logoLight: '',
  logoDark: '',
})

// 从 window.__SITE_CONFIG__ 获取后端注入的配置
function initFromServerConfig(): boolean {
  const config = (window as any).__SITE_CONFIG__ as SiteConfig | undefined
  if (config) {
    if (config.siteName) {
      siteSettings.siteName = config.siteName
      document.title = config.siteName
    }
    if (config.siteDescription) {
      siteSettings.siteDescription = config.siteDescription
    }
    if (config.logoLight) {
      siteSettings.logoLight = config.logoLight
      siteSettings.siteLogo = config.logoLight
    }
    if (config.logoDark) {
      siteSettings.logoDark = config.logoDark
    }
    if (config.favicon) {
      siteSettings.siteFavicon = config.favicon
      updateFavicon(config.favicon)
    }
    return true
  }
  return false
}

// 从 localStorage 获取缓存的设置（作为备用）
function initFromLocalStorage(): boolean {
  const storedSettings = localStorage.getItem('systemSettings')
  if (storedSettings) {
    try {
      const parsed = JSON.parse(storedSettings)
      if (parsed.site_name && !siteSettings.siteName) {
        siteSettings.siteName = parsed.site_name
      }
      if (parsed.site_description && !siteSettings.siteDescription) {
        siteSettings.siteDescription = parsed.site_description
      }
      if (parsed.site_logo && !siteSettings.siteLogo) {
        siteSettings.siteLogo = parsed.site_logo
      }
      if (parsed.site_favicon && !siteSettings.siteFavicon) {
        siteSettings.siteFavicon = parsed.site_favicon
      }
      return true
    }
    catch (e) {
      console.error('Failed to parse systemSettings from localStorage', e)
    }
  }
  return false
}

function updateFavicon(favicon: string) {
  if (!favicon)
    return

  const head = document.getElementsByTagName('head')[0]

  // 移除旧的 favicon
  const existingLinks = head.querySelectorAll('link[rel*="icon"]')
  existingLinks.forEach((link) => link.remove())

  // 添加新的 favicon
  const link = document.createElement('link')
  link.type = 'image/x-icon'
  link.rel = 'shortcut icon'
  link.href = getFileUrl(favicon)
  head.appendChild(link)

  const linkIcon = document.createElement('link')
  linkIcon.type = 'image/x-icon'
  linkIcon.rel = 'icon'
  linkIcon.href = getFileUrl(favicon)
  head.appendChild(linkIcon)
}

// 初始化系统设置
function initSiteSettings() {
  // 优先从后端注入的配置获取
  initFromServerConfig()

  // 如果后端没有注入配置，从 localStorage 获取
  if (!siteSettings.siteName) {
    initFromLocalStorage()
  }

  // 监听设置变化（来自系统设置页面的更新）
  window.addEventListener('system-settings-changed', ((event: CustomEvent) => {
    const settings = event.detail
    if (settings.site_name) {
      siteSettings.siteName = settings.site_name
    }
    if (settings.site_description) {
      siteSettings.siteDescription = settings.site_description
    }
    if (settings.site_logo) {
      siteSettings.siteLogo = settings.site_logo
      siteSettings.logoLight = settings.site_logo
    }
    if (settings.site_favicon) {
      siteSettings.siteFavicon = settings.site_favicon
      updateFavicon(settings.site_favicon)
    }
  }) as EventListener)
}

// 获取带页面标题的完整标题
function getPageTitle(pageTitle?: string): string {
  if (pageTitle && siteSettings.siteName) {
    return `${pageTitle} - ${siteSettings.siteName}`
  }
  if (siteSettings.siteName) {
    return siteSettings.siteName
  }
  return pageTitle || ''
}

// 获取 logo（根据主题自动选择）
function getLogo(isDark: boolean): string {
  if (isDark && siteSettings.logoDark) {
    return getFileUrl(siteSettings.logoDark)
  }
  if (siteSettings.logoLight) {
    return getFileUrl(siteSettings.logoLight)
  }
  if (siteSettings.siteLogo) {
    return getFileUrl(siteSettings.siteLogo)
  }
  return ''
}

export function useSiteSettings() {
  return {
    siteSettings,
    initSiteSettings,
    getPageTitle,
    getLogo,
  }
}