<script setup lang="ts">
import { computed } from "vue";
import Input from "../ui/Input.vue";
import { useHierarchyContext } from "@/composables/useHierarchyContext";
import { useFormSlugBase } from "@/composables/useFormSlugBase";
import { toSlug } from "@/lib/slug";
import type { FieldDefinition } from "./types";

const props = defineProps<{
  field: FieldDefinition;
  modelValue?: unknown;
  error?: string;
}>();

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

function handleBlur(e: FocusEvent): void {
  if (!props.field.generateFrom) {
    return;
  }
  const raw = (e.target as HTMLInputElement).value;
  const formatted = toSlug(raw);
  if (formatted !== raw) {
    emit("update:modelValue", formatted);
  }
}

const hierarchyCtx = useHierarchyContext();
const formSlugBase = useFormSlugBase();

// Show slug prefix when this field is auto-generated (slug-type) and a parent is selected.
const slugPrefix = computed<string>(() => {
  if (!props.field.generateFrom || !hierarchyCtx) return "";
  return hierarchyCtx.parentSlugPrefix.value;
});

// Full URL preview shown below the slug input whenever generateFrom is set.
const fullSlugPreview = computed<string>(() => {
  if (!props.field.generateFrom) return "";
  const local = String(props.modelValue ?? "");
  const parts = [formSlugBase?.value ?? "", slugPrefix.value, local].filter(
    Boolean,
  );
  return parts.join("/");
});
</script>

<template>
  <div>
    <Input
      type="text"
      :id="field.name"
      :name="field.name"
      :value="props.modelValue as string"
      :readonly="field.readonly"
      @input="
        $emit('update:modelValue', ($event.target as HTMLInputElement).value)
      "
      @blur="handleBlur"
    />

    <p
      v-if="fullSlugPreview"
      class="mt-1.5 font-mono text-xs text-muted-foreground break-all"
    >
      {{ fullSlugPreview }}
    </p>
  </div>
</template>
