<template>
	<label
		class="focus-within:ring-4 focus-within:ring-offset-2 ring-gray-500 relative w-full border border-gray-500 rounded-md cursor-text h-12 overflow-hidden"
	>
		<span :class="spanClasses" class="absolute left-2 top-0 transition-all select-none">{{ label }}</span>
		<input
			:value="modelValue"
			@input="update(($event.target as HTMLInputElement).value)"
			:required="required"
			class="outline-none w-full h-full rounded-sm pt-4 p-2 border-transparent"
			placeholder=""
			:autocomplete="autocomplete"
			:aria-label="label"
			@focus="inputFocused = true"
			@blur="inputFocused = false"
		/>
	</label>
</template>

<script setup lang="ts">
type Autocomplete =
	| "given-name"
	| "family-name"
	| "email"
	| "tel"
	| "street-address"
	| "postal-code"
	| "country-name"
	| "off"
	| "on"
	| "name"
	| "address-level2"
	| "country";

const props = withDefaults(
	defineProps<{
		modelValue?: string;
		label?: string;
		required?: boolean;
		labelClass?: string;
		inputClass?: string;
		autocomplete?: Autocomplete;
	}>(),
	{
		autocomplete: "off"
	}
);

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

const inputFocused = ref(false);

const spanClasses = computed(() => ({
	"text-md pt-3": !inputFocused.value && !props.modelValue,
	"text-xs pt-[3px]": inputFocused.value || props.modelValue,
	"text-gray-500": !inputFocused.value && !props.modelValue,
	"text-gray-400": inputFocused.value || props.modelValue
}));

function update(newValue?: string) {
	if (newValue !== undefined) {
		emit("update:modelValue", newValue);
	}
}
</script>
