<template>
  <div class="relative">
    <FormKit
      type="select"
      v-model="selectedEnvironment"
      :options="environmentOptions"
      placeholder="No Environment"
      outer-class="!mb-0 w-48"
      inner-class="!mb-0"
    />
    
    <rs-button
      variant="text"
      size="sm"
      @click="showEnvironmentModal = true"
      class="absolute right-8 top-1/2 transform -translate-y-1/2 p-1"
    >
      <Icon name="ic:outline-settings" size="14" />
    </rs-button>

    <!-- Environment Management Modal -->
    <EnvironmentModal
      v-if="showEnvironmentModal"
      @close="showEnvironmentModal = false"
    />
  </div>
</template>

<script setup>
import EnvironmentModal from './EnvironmentModal.vue'

const { environments, selectedEnvironment } = useApiPlatform()
const showEnvironmentModal = ref(false)

// Compute environment options for the dropdown
const environmentOptions = computed(() => {
  const options = [{ label: 'No Environment', value: '' }]
  environments.value.forEach(env => {
    options.push({ label: env.name, value: env.id })
  })
  return options
})

// Load environments from localStorage on mount
onMounted(() => {
  const saved = localStorage.getItem('api-platform-environments')
  if (saved) {
    try {
      const parsed = JSON.parse(saved)
      environments.value.splice(0, environments.value.length, ...parsed)
    } catch (e) {
      console.error('Failed to load environments:', e)
    }
  }
})

// Watch for environment changes and save to localStorage
watch(environments, (newEnvironments) => {
  localStorage.setItem('api-platform-environments', JSON.stringify(newEnvironments))
}, { deep: true })
</script> 