import './assets/main.css'
import './styles/fonts.css'
import './styles/global.css'

import { logEnvInfo } from './utils/env.js'
import { installProtectedAssetRuntime } from './utils/protectedAssetRuntime.js'
import { installRuntimeSecurity } from './utils/runtimeSecurity.js'
import { applyPerformanceModeClass } from './utils/performanceMode.js'
import { versionChecker } from './utils/versionChecker.js'
import { smartImage } from './directives/smartImage.js'
import { vTouchTap } from './utils/touchTap.js'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import { useLangStore } from '@/stores/lang'
import i18n, { initI18n, setLocale } from './locales/i18n'

import App from './App.vue'
import LoadingContent from './components/LoadingContent.vue'
import router from './router'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

logEnvInfo()
installRuntimeSecurity()
installProtectedAssetRuntime()
applyPerformanceModeClass()

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

const app = createApp(App)
app.directive('smart-img', smartImage)
app.directive('touch-tap', vTouchTap)
app.component('LoadingContent', LoadingContent)

app.use(router)
app.use(pinia)

const langStore = useLangStore()

const rankingPages = []
const activities = ['/recharge-reward']
const enPages = [...rankingPages, ...activities]
const arPages = []

const hashPath = window.location.hash.replace('#', '')
const currentPage = hashPath.split('?')[0]
const queryParams = hashPath.split('?')[1]
const urlParams = queryParams ? new URLSearchParams(queryParams) : new URLSearchParams()
const langParam = urlParams.get('lang')

let finalLang = null
if (langParam) {
  if (langParam === 'en') {
    finalLang = 'en'
  } else if (langParam.startsWith('ar')) {
    finalLang = 'ar'
  } else if (langParam === 'tr') {
    finalLang = 'tr'
  } else if (langParam === 'bn') {
    finalLang = 'bn'
  } else if (langParam.startsWith('pt')) {
    // Portuguese regional variants (for example pt-BR and pt-PT) share one translation pack.
    finalLang = 'pt'
  }
}

if (enPages.includes(currentPage)) {
  setLocale(langStore, 'en')
} else if (arPages.includes(currentPage)) {
  setLocale(langStore, 'ar')
} else if (finalLang) {
  console.log('langParam:', langParam)
  console.log('finalLang:', finalLang)
  setLocale(langStore, finalLang)
}

initI18n(langStore)

app.use(i18n)
app.mount('#app')

function runWhenIdle(callback) {
  if (typeof window.requestIdleCallback === 'function') {
    window.requestIdleCallback(callback, { timeout: 2000 })
    return
  }

  window.setTimeout(callback, 0)
}

async function checkVersionInBackground() {
  try {
    if (await versionChecker.checkVersion()) {
      console.log('Version updated')
    }
  } catch (error) {
    console.warn('Version check failed:', error)
  }
}

runWhenIdle(() => {
  void checkVersionInBackground()
})

if (versionChecker.enableCheck) {
  setInterval(
    async () => {
      try {
        const versionResult = await versionChecker.checkServerVersion()
        if (versionResult.shouldUpdate) {
          await versionChecker.handleVersionUpdate(versionResult.versionType)
        }
      } catch (error) {
        console.warn('Scheduled version check failed:', error)
      }
    },
    5 * 60 * 1000,
  )
}
