import { create } from 'zustand'
import api from '../api/client'

export const useSettingsStore = create((set, get) => ({
  settings: {},
  loaded: false,

  fetchSettings: async () => {
    try {
      const resp = await api.getSettings()
      set({ settings: resp.data || {}, loaded: true })
    } catch {
      // ignore - settings not available before login
    }
  },

  getSetting: (key, fallback = '') => {
    return get().settings[key] || fallback
  },

  getBackendHost: () => {
    const url = get().settings.backend_url_internal || ''
    try {
      return new URL(url).hostname
    } catch {
      // fallback: strip protocol and port manually
      return url.replace(/^https?:\/\//, '').replace(/:\d+$/, '')
    }
  },
}))
