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

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  icon: {
    type: String,
    default: '',
  },
  collapsible: {
    type: Boolean,
    default: false,
  },
  defaultCollapsed: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['toggle'])

const isCollapsed = ref(props.defaultCollapsed)

function toggleCollapse() {
  if (props.collapsible) {
    isCollapsed.value = !isCollapsed.value
    emit('toggle', isCollapsed.value)
  }
}
</script>

<template>
  <div class="card-header" @click="toggleCollapse">
    <div class="card-header__title">
      <slot name="icon">
        <van-icon v-if="icon" class="card-header__icon" :name="icon" />
      </slot>
      <h4 class="card-header__text">
        {{ title }}
      </h4>
    </div>
    <div class="card-header__extra">
      <slot name="extra" />
      <van-icon
        v-if="collapsible"
        class="card-header__collapse-icon"
        :name="isCollapsed ? 'arrow-down' : 'arrow-up'"
      />
    </div>
  </div>
</template>

<style lang="less" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;

  &__title {
    display: flex;
    align-items: center;
  }

  &__icon {
    margin-right: 8px;
    font-size: 14px;
    color: #666;
  }

  &__text {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }

  &__extra {
    display: flex;
    align-items: center;
  }

  &__collapse-icon {
    margin-left: 8px;
    font-size: 14px;
    color: #666;
    cursor: pointer;

    &:hover {
      color: #333;
    }
  }
}
</style>
