<script lang="ts" setup>

// types

type Props = {
    modelValue: number;
    max: number;
    disable: boolean;
}

// props

const props = defineProps<Props>();
const { modelValue, max } = toRefs(props);

// state

const timer = ref<NodeJS.Timeout | null>(null);

// emit

const emit = defineEmits(["update:modelValue"]);

// computed

const currentQuantity = computed({
    get: () => modelValue.value ?? 0,
    set: (value: number) => {
        if (timer.value) clearTimeout(timer.value);
        timer.value = setTimeout(() => {
            emit("update:modelValue", value);
        }, 50);
    }
});

// methods

const onInput = (e: any) => {
    const value = Number(e.target.value);
    if (value > 0 && value <= max.value) {
        currentQuantity.value = value;
    } else {
        currentQuantity.value = 1;
    }
};


</script>

<template>
    <NumberFieldRoot
        :disabled="disable"
        class="rounded-full border-slate-200 border-[1.5px] flex items-center bg-white gap-4  p-4 max-sm:h-[48px]"
        v-model="currentQuantity"
        :min="1"
        :max="max"
    >
        <NumberFieldIncrement class="cursor-pointer">
            <Icon name="ci:plus" class="**:stroke-slate-500 size-5" />
        </NumberFieldIncrement>
        <NumberFieldInput
            @input="onInput"
            class="field-sizing-content w-[30px] bg-transparent text-center outline-none typo-label-md text-black"
        />
        <NumberFieldDecrement class="cursor-pointer">
            <Icon name="ci:minus" class="**:stroke-slate-500 size-5" />
        </NumberFieldDecrement>
    </NumberFieldRoot>
</template>