import { ref } from 'vue'
import { get } from '@/utils/request'
import { PUBLIC_MENUS } from '@/config/menus'

export type PublicSettings = Record<string, string>

const cache = ref<PublicSettings>({})
const loaded = ref(false)

export function usePublicSettings() {
  const load = async (force = false) => {
    if (loaded.value && !force) return cache.value
    try {
      const data = await get<PublicSettings>('/settings')
      cache.value = data || {}
      loaded.value = true
    }
    catch {
      cache.value = {}
    }
    return cache.value
  }

  const getStringSetting = (key: string, fallback = '') => cache.value[key] || fallback

  const getVisibleMenus = (): string[] => {
    const raw = getStringSetting('visible_menus')
    const defaults = ['home', 'blog', 'columns', 'works', 'videos', 'snippets', 'about', 'services']
    if (!raw) return defaults
    try {
      const parsed = JSON.parse(raw)
      if (Array.isArray(parsed)) return parsed
    }
    catch {
      return raw.split(',').map(s => s.trim()).filter(Boolean)
    }
    return defaults
  }

  const getExploreMenus = () => {
    const visible = getVisibleMenus()
    return PUBLIC_MENUS.filter(m => visible.includes(m.key))
  }

  return {
    cache,
    loaded,
    load,
    getStringSetting,
    getVisibleMenus,
    getExploreMenus,
  }
}
