<template>
  <view
    class="sticky top-0 z-40"
    :class="props.gradient ? '' : 'bg-white border-b border-gray-100'"
    :style="props.gradient ? { background: 'linear-gradient(135deg, #3b82f6, #2563eb)' } : {}"
  >
    <view class="status-bar" :style="{ height: `${statusBarHeight}px` }"></view>
    <view class="top-bar px-4 flex items-center justify-between">
      <view class="flex items-center flex-1 min-w-0">
        <view
          v-if="showBack"
          class="mr-2 p-2 -ml-2 clickable rounded-lg"
          @click="goBack"
        >
          <uni-icons
            type="left"
            size="20"
            :color="props.gradient ? '#ffffff' : '#4b5563'"
          />
        </view>
        <slot name="left" />
        <text
          class="text-base font-semibold truncate"
          :class="props.gradient ? 'text-white' : 'text-gray-800'"
        >
          {{ title }}
        </text>
      </view>
      <CapsuleSafeArea>
        <view class="flex items-center">
          <slot name="right" />
        </view>
      </CapsuleSafeArea>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import CapsuleSafeArea from './CapsuleSafeArea.vue'

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

const statusBarHeight = ref(0)

onMounted(() => {
  try {
    const info = uni.getSystemInfoSync()
    statusBarHeight.value = info.statusBarHeight || 0
  } catch (e) {
    statusBarHeight.value = 0
  }
})

function goBack() {
  if (!props.showBack) return
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack({ delta: 1 })
  } else {
    uni.switchTab({ url: '/pages/home/home' })
  }
}
</script>

<style scoped>
.top-bar {
  height: 44px;
}
</style>
