<script setup lang="ts">
import { computed } from 'vue'

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

const emit = defineEmits<{
  (e: 'back'): void
}>()

const router = useRouter()

const nativeSafeArea = useState<{ top: number, bottom: number }>('native-safe-area')
const headerStyle = computed<Partial<Record<string, string>>>(() => {
  if (!nativeSafeArea.value) return {}

  return {
    paddingTop: `${nativeSafeArea.value.top}px`,
    height: `calc(44px + ${nativeSafeArea.value.top}px)`,
  }
})

const handleBack = () => {
  emit('back')
  if (props.disableDefaultBack) return
  router.back()
}
</script>

<template>
  <header
    class="common-header"
    :style="headerStyle"
  >
    <button
      v-if="props.showBack"
      type="button"
      class="common-header__back"
      @click="handleBack"
    >
      <van-icon
        name="arrow-left"
        :size="18"
      />
    </button>
    <div
      v-else
      class="common-header__spacer"
    />

    <h1 class="common-header__title">
      {{ props.title }}
    </h1>

    <div class="common-header__spacer">
      <slot name="right" />
    </div>
  </header>
</template>

<style scoped lang="scss">
.common-header {
  position: sticky;
  top: 0;
  z-index: 10;
  box-sizing: border-box;
  height: calc(44px + env(safe-area-inset-top));
  padding-top: env(safe-area-inset-top);
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}

.common-header__back {
  border: none;
  padding: 4px;
  border-radius: 999px;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.common-header__title {
  font-size: 18px;
  font-weight: 500;
  color: #17171a;
}

.common-header__spacer {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
