<template>
  <template v-if="display">
    <PageLoader v-if="hasPageLoader" />
    <TopWideMenu v-if="display === 'big-menu'" />
    <SideMenuWithCategories v-else-if="display === 'side-with-categories'" />
    <SimpleSideMenu
      v-else-if="display === 'simple-side-menu'"
      :alawayDisplayed="display === 'always-displayed'"
    />
  </template>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useConfigStore } from '../store/config.js'
import { createElement } from '../lib/dom.js'
import { translate as t } from '@nextcloud/l10n'

import SimpleSideMenu from './SimpleSideMenu'
import TopWideMenu from './TopWideMenu'
import SideMenuWithCategories from './SideMenuWithCategories'
import PageLoader from '../components/PageLoader'

const config = ref(null)
const configStore = useConfigStore()
const display = ref(null)
const alawayDisplayed = ref(false)
const hasPageLoader = ref(false)
const createOpener = () => {
  const nextcloud = document.querySelector('#nextcloud')
  const logo = document.querySelector('.header-left .logo, .header-start .logo')

  if (!nextcloud || !logo) {
    return
  }

  if (logo.parentNode !== nextcloud) {
    nextcloud.appendChild(logo)
  }

  const opener = createElement('button', {
    'class': 'side-menu-opener',
    'arial-label': t('side_menu', 'Toggle the menu'),
    'html': `<span>${t('side_menu', 'Toggle the menu')}</span>`
  })

  if (config.value['opener-position'] === 'before') {
    nextcloud.parentNode.insertBefore(opener, nextcloud)
  } else {
    nextcloud.parentNode.insertBefore(opener, nextcloud.nextSibling)
  }
}

const createLoader = () => {
  const loader = createElement('div', { id: 'side-menu-loader' })
  const bar = createElement('div', { id: 'side-menu-loader-bar' })

  loader.appendChild(bar)
  document.querySelector('body').appendChild(loader)

  let pageLoaderValue = 0

  window.addEventListener('beforeunload', () => {
    setInterval(() => {
      pageLoaderBar.style.width = pageLoaderValue.toString() + '%'
      pageLoaderValue = Math.min(pageLoaderValue + 0.2, 100)
    }, 25)
  })
}

onMounted(async () => {
  config.value = await configStore.getConfig()

  if (config.value['big-menu']) {
    display.value = 'big-menu'
  } else if (config.value['side-with-categories']) {
    display.value = 'side-with-categories'
  } else {
    display.value = 'simple-side-menu'
    alawayDisplayed.value = config.value['always-displayed']
  }

  hasPageLoader.value = config.value['loader-enabled']

  createOpener()
})
</script>
