import axios from 'axios'

const client = axios.create({ baseURL: '' })

client.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

client.interceptors.response.use(
  res => res,
  err => {
    if (!err.response) {
      window.dispatchEvent(new Event('backend-offline'))
    } else if (err.response.status === 401) {
      // Token expired or user blocked — force logout
      localStorage.removeItem('token')
      localStorage.removeItem('savedUsername')
      window.location.href = '/login'
    }
    return Promise.reject(err)
  }
)

export default client
