import { onMounted, ref } from 'vue'
import { getPublicSettings, type PublicSettings } from '../services/api'

const cache = ref<PublicSettings | null>(null)
let loading: Promise<PublicSettings> | null = null
let listenerRegistered = false

function registerSettingsListener() {
  if (typeof window === 'undefined' || listenerRegistered) return
  listenerRegistered = true
  window.addEventListener('public-settings-changed', () => {
    cache.value = null
    loading = null
    void loadPublicSettings(true)
  })
}

export async function loadPublicSettings(force = false): Promise<PublicSettings> {
  if (!force && cache.value) return cache.value
  if (!force && loading) return loading

  loading = getPublicSettings().then(data => {
    cache.value = data
    loading = null
    return data
  })

  return loading
}

export function usePublicSettings() {
  onMounted(() => {
    void loadPublicSettings()
    registerSettingsListener()
  })

  const load = loadPublicSettings

  const invalidate = () => {
    cache.value = null
    loading = null
  }

  const getStringSetting = (key: keyof PublicSettings, fallback = ''): string => {
    const raw = cache.value?.[key]
    if (raw == null || String(raw).trim() === '') return fallback
    return String(raw)
  }

  const getNumberSetting = (key: keyof PublicSettings, fallback: number): number => {
    const raw = cache.value?.[key]
    if (!raw) return fallback
    const n = parseInt(String(raw), 10)
    return Number.isFinite(n) && n > 0 ? n : fallback
  }

  return { cache, load, invalidate, getStringSetting, getNumberSetting }
}
