<template>
  <view class="uni-segmented-control">
    <view 
      v-for="(item, index) in values" 
      :key="index"
      class="uni-segmented-control__item"
      :class="{ 
        'uni-segmented-control__item--active': currentIndex === index,
        'uni-segmented-control__item--disabled': disabled
      }"
      :style="itemStyle(index)"
      @click="onClick(index)"
    >
      <text class="uni-segmented-control__text" :style="textStyle(index)">
        {{ item }}
      </text>
    </view>
  </view>
</template>

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

interface Props {
  current: number
  values: string[]
  activeColor?: string
  styleType?: 'button' | 'text'
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  current: 0,
  activeColor: '#4f8ef7',
  styleType: 'button',
  disabled: false
})

const emit = defineEmits<{
  clickItem: [index: number]
}>()

const currentIndex = computed(() => props.current)

function itemStyle(index: number) {
  if (props.styleType === 'text') return {}
  const isActive = currentIndex.value === index
  return {
    backgroundColor: isActive ? props.activeColor : 'transparent',
    borderColor: props.activeColor
  }
}

function textStyle(index: number) {
  const isActive = currentIndex.value === index
  if (props.styleType === 'text') {
    return {
      color: isActive ? props.activeColor : '#666',
      borderBottom: isActive ? `2px solid ${props.activeColor}` : '2px solid transparent'
    }
  }
  return {
    color: isActive ? '#fff' : props.activeColor
  }
}

function onClick(index: number) {
  if (props.disabled) return
  emit('clickItem', index)
}
</script>

<style scoped>
.uni-segmented-control {
  display: flex;
  flex-direction: row;
  background-color: #fff;
  padding: 8px 16px;
}
.uni-segmented-control__item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 0;
  border: 1px solid;
  border-right-width: 0;
  cursor: pointer;
  transition: all 0.3s;
}
.uni-segmented-control__item:first-child {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}
.uni-segmented-control__item:last-child {
  border-right-width: 1px;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}
.uni-segmented-control__item--disabled {
  opacity: 0.5;
}
.uni-segmented-control__text {
  font-size: 14px;
  transition: all 0.3s;
}
</style>
