<template>
  <div
    :class="{ '--small': small }"
    class="ui-segmented"
  >
    <span
      v-if="title"
      class="ui-segmented__label"
    >
      <UiIcon
        v-if="icon"
        :name="icon"
        :prefix="iconPrefix"
        class="ui-segmented__label-icon"
        size="16"
      />
      {{ title }}
    </span>
    <div class="ui-segmented__wrapper">
      <button
        v-for="(item, index) in items"
        :key="`${item.name}=${index}`"
        :class="{'--active': modelValue === item.name}"
        class="ui-segmented__button"
        type="button"
        @click="onButtonClick(item)"
      >
        {{ item.title }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { IModelFilterOptions } from '../../types';

defineProps<{
  items: IModelFilterOptions[]
  title?: string
  modelValue: string
  small?: boolean
  icon?: string
  iconPrefix?: string
}>();

const emit = defineEmits<{
  (eventName: 'update:modelValue', value: string): void,
}>();

function onButtonClick(item: IModelFilterOptions) {
  emit('update:modelValue', item.name);
}
</script>

<style lang="scss">
.ui-segmented {
  display: grid;
}

.ui-segmented__label {
  @include font-sm;

  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  column-gap: 8px;
  margin-bottom: 8px;
  color: $segmented-label;
}

.ui-segmented__label-icon {
  flex-shrink: 0;
  color: $segmented-label-icon;
}

.ui-segmented__wrapper {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  border-radius: $radius-lg;
  justify-content: space-between;
  background-color: $segmented-bg;
  overflow: hidden;
}

.ui-segmented__button {
  @include font-xs;

  flex-grow: 1;
  padding: 8px;
  height: 32px;
  color: $segmented-text;
  border-radius: $radius-md;

  @include hover(color) {
    color: $segmented-text--hover;
  }
}

.--small {
  background-color: $segmented-bg--small;
}

.--small .ui-segmented__button {
  @include font-xs;

  display: grid;
  place-content: center;
  border-radius: $radius-small;
  font-weight: 500;
  padding: 4px 0;
  min-width: 40px;
  height: 24px;
}

.ui-segmented__button.--active {
  background-color: $segmented-bg--active;
  color: $segmented-text--active;
}

.--small .ui-segmented__wrapper {
  border-radius: $radius-small;
  background-color: transparent;
}
</style>
