<script setup lang="ts">
import { ref, onMounted } from "vue";
import { apiGet } from "@/api/client";

interface Project {
  id: number;
  title: string;
  status: string;
}

defineProps<{
  modelValue: number | null;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: number | null): void;
}>();

const projects = ref<Project[]>([]);
let cacheExpiry = 0;

async function loadProjects() {
  const now = Date.now();
  if (projects.value.length > 0 && now < cacheExpiry) return;
  try {
    const data = await apiGet<{ projects: Project[] }>("/api/projects?status=active");
    projects.value = data.projects;
    cacheExpiry = now + 60_000; // 60 second cache
  } catch {
    // Silently fail — selector will just be empty
  }
}

onMounted(loadProjects);

function onChange(e: Event) {
  const value = (e.target as HTMLSelectElement).value;
  emit("update:modelValue", value ? Number(value) : null);
}
</script>

<template>
  <select class="project-selector" :value="modelValue ?? ''" @change="onChange">
    <option value="">No project</option>
    <option v-for="project in projects" :key="project.id" :value="project.id">
      {{ project.title }}
    </option>
  </select>
</template>

<style scoped>
.project-selector {
  padding: 0.4rem 0.5rem;
  border: 1px solid var(--fs-border-color);
  border-radius: var(--fs-radius-sm);
  background: var(--fs-surface-raised);
  color: var(--fs-text-primary);
  font-size: 0.9rem;
  font-family: inherit;
  width: 100%;
  box-sizing: border-box;
}
.project-selector:focus {
  outline: none;
  border-color: var(--fs-accent);
}
</style>
