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

import { Select, message } from 'antdv-next';

import {
  DEV_API_OPTIONS,
  getDevApiTargetLabel,
  getStoredDevApiTarget,
  isDevApiSwitchEnabled,
  normalizeDevApiTarget,
  type DevApiTarget,
  setStoredDevApiTarget,
} from '#/config/dev-api-switch';

defineOptions({
  name: 'DevApiSwitch',
});

const enabled = isDevApiSwitchEnabled();
const currentTarget = ref<DevApiTarget>(getStoredDevApiTarget());

function handleChange(value: string) {
  const nextTarget = normalizeDevApiTarget(value);
  if (nextTarget === currentTarget.value) {
    return;
  }
  currentTarget.value = nextTarget;
  setStoredDevApiTarget(nextTarget);
  message.success(`已切换到${getDevApiTargetLabel(nextTarget)}，后续请求将使用对应环境`);
}
</script>

<template>
  <div v-if="enabled" class="dev-api-switch">
    <span class="dev-api-switch__label">API</span>
    <Select
      :value="currentTarget"
      :options="DEV_API_OPTIONS"
      class="dev-api-switch__select"
      option-label-prop="label"
      size="small"
      @change="handleChange"
    />
  </div>
</template>

<style scoped>
.dev-api-switch {
  align-items: center;
  display: flex;
  gap: 8px;
  height: 100%;
}

.dev-api-switch__label {
  color: var(--vben-layout-header-text-color, rgb(15 23 42 / 0.72));
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.08em;
}

.dev-api-switch__select {
  width: 128px;
}
</style>
