<template>
  <view class="budget-bar-wrap">
    <view class="bar-track">
      <view class="bar-fill" :class="{ over: rawPercentage > 100 }" :style="{ width: percentage + '%' }"></view>
    </view>
    <view class="bar-info" v-if="showLabel">
      <text class="bar-text" v-if="rawPercentage <= 100">预算 {{ formatAmount(total) }} · 剩余 {{ formatAmount(Math.max(0, total - used)) }}</text>
      <text class="bar-text over" v-else>已超支 {{ formatAmount(used - total) }}</text>
      <text class="bar-pct" :class="{ over: rawPercentage > 100 }">{{ rawPercentage }}%</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { formatAmount } from '@/utils/format'

const props = withDefaults(defineProps<{
  total: number
  used: number
  showLabel?: boolean
}>(), { showLabel: true })

const rawPercentage = computed(() => {
  if (props.total <= 0) return 0
  return Math.round((props.used / props.total) * 100)
})

const percentage = computed(() => Math.min(100, rawPercentage.value))
</script>

<style lang="scss" scoped>
.bar-track {
  height: 16rpx;
  border-radius: 8rpx;
  background: $border;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 8rpx;
  background: linear-gradient(90deg, $primary, lighten($primary, 15%));
  transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);

  &.over {
    background: $danger;
  }
}

.bar-info {
  display: flex;
  justify-content: space-between;
  margin-top: 16rpx;
}

.bar-text {
  font-size: 24rpx;
  color: $text-sec;
}

.bar-pct {
  font-family: 'Fredoka', sans-serif;
  font-size: 28rpx;
  font-weight: 500;
  color: $primary;

  &.over { color: $danger; }
}

.bar-text.over {
  color: $danger;
  font-weight: 500;
}
</style>
