<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useAppTabbar } from '@/composables/useAppTabbar'
import { useTheme } from '@/composables/useTheme'
import { useAppMode } from '@/composables/useAppMode'

const props = withDefaults(defineProps<{ hidden?: boolean }>(), { hidden: false })

const { tabItems, resolveActive, navigateTab, shouldShowTabbar } = useAppTabbar()
const { isDark } = useTheme()
const { appMode } = useAppMode()

const active = ref('home')
const visible = ref(true)

const accent = '#d4b383'
const inactive = computed(() => (isDark.value || appMode.value === 'admin' ? '#888888' : '#6b6b6b'))
const barStyle = computed(() => {
  const dark = isDark.value || appMode.value === 'admin'
  const bg = dark ? 'rgba(18,18,20,0.95)' : 'rgba(255,255,255,0.95)'
  return `background:${bg};backdrop-filter:blur(20px);`
})

const refresh = () => {
  const pages = getCurrentPages()
  const cur = pages[pages.length - 1] as { route?: string } | undefined
  const path = cur?.route ? `/${cur.route}` : ''
  active.value = resolveActive(path)
  visible.value = !props.hidden && shouldShowTabbar(path)
}

onShow(refresh)
watch(() => props.hidden, refresh)
watch(isDark, refresh)

const onChange = ({ value }: { value: string | number }) => {
  navigateTab(String(value))
}
</script>

<template>
  <wd-tabbar
    v-if="visible"
    v-model="active"
    shape="round"
    fixed
    :bordered="false"
    :active-color="accent"
    :inactive-color="inactive"
    safe-area-inset-bottom
    :z-index="500"
    :custom-style="barStyle"
    @change="onChange"
  >
    <wd-tabbar-item
      v-for="item in tabItems"
      :key="item.name"
      :name="item.name"
      :title="item.title"
      :icon="item.icon"
    />
  </wd-tabbar>
</template>
