<script setup lang="ts">
/**
 * Stores a URL string but delegates picking to the standard FieldMediaInput
 * component (registered by the media package). When the user picks an image,
 * we resolve its URL via the media API and emit it.
 */
import { computed, ref, watch } from "vue";
import { useBuilderPrefix, registry } from "@builder/ui";

const props = defineProps<{
  field: { name: string; label: string; [key: string]: unknown };
  modelValue?: string | null;
  error?: string;
}>();

const emit = defineEmits<{
  "update:modelValue": [value: string | null];
}>();

const prefix = useBuilderPrefix();

const mediaInputComponent = computed(() =>
  registry.resolveComponent("FieldMediaInput"),
);

// The picker is stateless — we pass null and listen for selection events.
const mediaId = ref<number | null>(null);

watch(mediaId, async (id) => {
  if (!id) return;

  try {
    const res = await fetch(`/${prefix}/media/file/${id}`, {
      headers: { Accept: "application/json" },
    });
    if (res.ok) {
      const data = await res.json();
      emit("update:modelValue", (data.url as string) ?? null);
    }
  } finally {
    mediaId.value = null;
  }
});

function clear(): void {
  emit("update:modelValue", null);
}
</script>

<template>
  <div class="space-y-2">
    <!-- Current image preview -->
    <div
      v-if="modelValue"
      class="flex items-center gap-3 rounded-md border p-2"
    >
      <img
        :src="modelValue"
        alt=""
        class="h-10 w-10 shrink-0 rounded object-cover"
      />
      <span class="min-w-0 flex-1 truncate text-xs text-muted-foreground">{{
        modelValue
      }}</span>
      <button
        type="button"
        class="shrink-0 text-xs text-muted-foreground hover:text-foreground"
        @click="clear"
      >
        ✕
      </button>
    </div>

    <!-- Standard media picker — always in "empty" state so clicking opens the picker -->
    <component
      :is="mediaInputComponent"
      v-if="mediaInputComponent"
      v-model="mediaId"
      :field="{ ...field, multiple: false }"
    />

    <p v-if="error" class="text-xs text-destructive">{{ error }}</p>
  </div>
</template>
