<script setup lang="ts">
/**
 * 全局导航栏封装：按主题注入 --wot-navbar-*，保证暗色下标题与返回箭头可见。
 * wd-navbar 内部用 CSS 变量着色，仅设 custom-style 的 color 往往无效。
 */
import { computed, toRefs } from 'vue'
import { useTheme } from '@/composables/useTheme'
import { useAppMode } from '@/composables/useAppMode'

const props = withDefaults(defineProps<{
  title?: string
  showBack?: boolean
  transparent?: boolean
}>(), {
  title: '',
  showBack: false,
  transparent: false,
})

const { transparent } = toRefs(props)
const emit = defineEmits<{ back: [] }>()
const { isDark } = useTheme()
const { appMode } = useAppMode()

/** 暗色：管理端或用户选深色主题 */
const dark = computed(() => isDark.value || appMode.value === 'admin')

/** 前景色：标题 / 箭头共用，保证对比度 */
const fg = computed(() => (dark.value ? '#ececec' : '#171717'))

/**
 * 通过 CSS 变量覆盖 wot-navbar 内部色；透明模式仍传前景色，避免黑底黑字。
 */
const navStyle = computed(() => {
  const color = fg.value
  const bg = transparent.value
    ? 'transparent'
    : (dark.value ? 'rgba(5,5,5,0.92)' : 'rgba(250,248,244,0.92)')
  return [
    `background:${bg}`,
    `background-color:${bg}`,
    `color:${color}`,
    `--wot-navbar-bg:${bg}`,
    `--wot-navbar-color:${color}`,
    `--wot-navbar-desc-color:${color}`,
  ].join(';')
})

/** 返回：有栈则返回，否则回首页 */
const onBack = () => {
  emit('back')
  const pages = getCurrentPages()
  if (pages.length > 1) uni.navigateBack()
  else uni.reLaunch({ url: '/pages/home/index' })
}
</script>

<template>
  <wd-navbar
    :title="title"
    :left-arrow="showBack"
    :bordered="false"
    safe-area-inset-top
    fixed
    placeholder
    :custom-style="navStyle"
    @click-left="onBack"
  >
    <!-- 插槽兜底：部分端上箭头仍不吃变量时，用显式色的图标 -->
    <template v-if="showBack" #left>
      <view class="nav-back" @click.stop="onBack">
        <wd-icon name="left" size="22px" :color="fg" />
      </view>
    </template>
    <template v-if="title" #title>
      <text class="nav-title" :style="{ color: fg }">{{ title }}</text>
    </template>
    <template v-if="$slots.right" #right>
      <slot name="right" />
    </template>
  </wd-navbar>
</template>

<style scoped lang="scss">
.nav-back {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
  height: 100%;
}
.nav-title {
  font-size: 34rpx;
  font-weight: 600;
  max-width: 60vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
