import './index.css'

import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import router from './router'
import App from './App.vue'

import {
  FrappeUI,
  Button,
  Input,
  TextInput,
  FormControl,
  ErrorMessage,
  Dialog,
  Alert,
  Badge,
  setConfig,
  frappeRequest,
  FeatherIcon,
  Tooltip,
  Spinner,
  TabButtons,
  Tabs,
} from 'frappe-ui'

// Import locales
import en from './locales/en.json'
import ru from './locales/ru.json'

// Setup i18n
const i18n = createI18n({
  legacy: false,
  locale: localStorage.getItem('admin-panel-locale') || 'ru',
  fallbackLocale: 'en',
  messages: {
    en,
    ru,
  },
})

const globalComponents = {
  Button,
  TextInput,
  Input,
  FormControl,
  ErrorMessage,
  Dialog,
  Alert,
  Badge,
  FeatherIcon,
  Tooltip,
  Spinner,
  TabButtons,
  Tabs,
}

const app = createApp(App)

setConfig('resourceFetcher', frappeRequest)
app.use(FrappeUI, {
  socketio: false,
})
app.use(router)
app.use(i18n)

for (const key in globalComponents) {
  app.component(key, globalComponents[key])
}

if (import.meta.env.DEV) {
  frappeRequest({
    url: '/api/method/admin_panel.www.admin.get_context_for_dev',
  })
    .then((values) => {
      for (const key in values) {
        window[key] = values[key]
      }
    })
    .catch((e) => {
      console.warn('Failed to fetch dev context:', e)
    })
    .finally(() => {
      app.mount('#app')
    })
} else {
  app.mount('#app')
}
